Previously I have worked with bog standard PHP and have recently made the move over to Laravel. One thing I cannot grasp is SQL queries in Laravel Eloquent.
For instance I have a roles and a users table. The roles table contains roles and IDs for each role. The users table contains various user details as well as a role_id to reference the role of the user.
What I have tried in my user model
public function role()
// return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
return $this->hasOne('App\Role', 'id', 'role_id');
public function users()
return $this->hasMany('App\User', 'role_id', 'id');
public function index()
$var = User::find()->role->get();
'var' => $var
You can access table fields via eloquent model attributes.
If you have fields like
$user = User::find(1); $name = $user->name; $email = $user->email; $roleName = $user->role->name;
Note that you do not really have to call
get() method on relation. Accessing it will call it automatically.