Jesse Orange Jesse Orange - 11 months ago 55
PHP Question

Understanding Eloquent in Laravel

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');

What I have tried in my role model

public function users()
return $this->hasMany('App\User', 'role_id', 'id');

Then in my controller

public function index()
$var = User::find()->role->get();

return view('article',
'var' => $var

But now how do I access the fields in both tables as I would in ordinary PHP? I would rather use standard SQL but am trying to properly learn this framework.

Any advice?

Answer Source

You can access table fields via eloquent model attributes.

If you have fields like name, email you can fetch them 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.

Laravel docs are pretty helpful in this matter. Laravel 5.2 Eloquent: Getting Started and Laravel 5.2 Eloquent: Relationships