Search code examples
phplaravelcontains

Reverse contains() in laravel?


I'm new to laravel, I'm trying to get a row from a table according to it's Many-to-Many relationship with another table.

You know when you pass multiple ids in contain() to check if they have relationship with that row or not, like this:

$row->contains([4,6,9]);

i want to reverse this, where i can use the ids [4,6,9] to get any row from the other table linked with them.


Solution

  • Let's say you have this two models: User and Role that makes many-to-many relationship.

    If you defined your relationships properly:

    /** User.php */
    
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
    

    -

    /** Role.php */
    
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
    

    Then you could use the relationship to accomplish what you are trying to do.

    From the related object:

    $user = User::find(1);
    
    // getting all the roles attached with a user:
    $roles = $user->roles;
    
    // getting all the roles attached with a user that has certain ids:
    $roles = $user->roles()->whereIn('id', [2, 4, 6])->get();
    

    Also, you could find your desired related model using the collection instance that return the relationship:

    $user = User::find(1);
    
    // getting all the roles attached with a user:
    $roles = $user->roles;
    
    // getting a specific role attached to a user:
    $specific_role = $roles->where('id', 6)->first();