0
votes

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', 
        array(
        '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?

2
change to hasOne('App\Role', 'role_id', 'id');, but in fact you can just ommit the keys and eloquent will guess them right in your case.Jarek Tkaczyk
Tell me what relation you want between role and user (1-1,1-n,n-n). I'll give u an exampleKmasterYC
I would use belongsTo('App\Role') for the role() relation. This is how a 1-to-many relationship is modelled on the many side.Jared Rolt

2 Answers

0
votes

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

0
votes

Try it with eager loading

$var = User::with('role')->find($userId)->get();