Search code examples
phplaravelforeign-keysentity-relationshiplaravel-artisan

Getting data from laravel relation on Foreign Key


I have to SQL tables: users and roles; The user table consists of an id (PRIMARY), email, password and a role_id (INDEX) column. The role table consists of an id (PRIMARY) and a name column. A user can only have a single role (Admin or User).

This is how my laravel Models look like:

// User Model
public function role()
{
    return $this->hasOne(Role::class);
}

// Role model
public function user()
{
    return $this->belongsTo(User::class);
}

What i want is, when i get the information of a user, i want to get the corresponding role of that user.

When i place this code in the Artisan Tinker:

// Get user with id=2
App\User::find(2)->role;

This seems logical to me "Find the role belonging to the user with id 2"

But it is throwing this error:

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from `roles` where `roles`.`user_id` = 2 and `roles`.`user_id` is not null limit 1)'

How Can i get the role of a User without calling it from the Role model?


Solution

  • Since you have a role_id on users table, you should have belongsTo(Role::class) on User model:

    // User Model
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
    

    And hasMany(User::class) on role model:

    // Role model
    public function users()
    {
        return $this->hasMany(User::class);
    }