Search code examples
phplaraveleloquenteloquent-relationship

Laravel Many To Many Relationship Check with intermediate table


i'm new here and very much hope i'm not asking a duplicate question.

I am completely new to coding and jumped right into Laravel, but now running into an issue that i'm not quite finding an answer for.

I have the following Model setup:

User.php

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles')->as('roles')->withTimestamps();
    }

Role.php

Has a table column 'name'

    public function users()
    {
        return $this->belongsToMany(User::class, 'user_roles');
    }

UserRole.php

Intermediate table with table columns 'user_id and 'role_id'

The issue that i'm facing is that i want to create a role check on the user, and i am guessing that creating a middleware will be the way to go. But when i want to check if a user has a role with the following code:

if (Auth::user()->roles->name == 'manager')
    {
        // do something here
    }
    else {
        // do something else here
    }

I get an error stating that 'name' does not exist on this collection instance.

I figured out that i can loop over the roles a user has and display them with:

$user = User::find(1);
foreach($user->roles as $role)
{
print $role->name;
}

But i'm completely clueless as to why the role check isn't working.


Solution

  • Auth::user()->roles is a collection of roles, an instance of Illuminate\Database\Eloquent\Collection. So for that check, you might want to do something like:

    if (Auth::user()->roles->contains('name', 'manager') {
        // do something here
    } else {
        // do something else here
    }