thitami
thitami

Reputation: 838

Laravel BelongsToMany method returns nothing

I am implementing a many-to-many relationship in Laravel. The entities are: users roles and pivot table user_role

Users
====
id
name
.....

roles
====
id
role
...

   user_role
   ======
   userId
   roleId

Trying various ways to get the roles of a user but no luck so far. Any ideas?

Last try is:

/**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_role', 'userId', 'roleId');
    }

Current output on Laravel Tinker:

>>> $user->roles()
=> Illuminate\Database\Eloquent\Relations\BelongsToMany {#2380
     +withTimestamps: false,

Upvotes: 1

Views: 2853

Answers (1)

gbalduzzi
gbalduzzi

Reputation: 10166

$user->roles() is just the query for the relationship, it is not executed

You can use

$user->roles

if you don't need to add extra conditions or

$user->roles()->where(your conditions)->get()

for a more complex relationship query.

The key difference is the usage of pharentesis: ->roles vs ->roles(). The former returns the query result, the latter the query itself

Upvotes: 6

Related Questions