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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

as Auth::user()->roles returns collection of all roles so you can not apply “==” operator directly

Method 2

Auth::user()->roles is a collection of roles, an instance of IlluminateDatabaseEloquentCollection. 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
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x