Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter many to many structure in Laravel

Tags:

php

laravel

I got a many to many user and role structure

users
id
name

roles
id
name

role_user
user_id
role_id

Model

User.php

public function roles() {
    return $this->belongsToMany('Role');
}

Role.php

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

There are two data admins and members in roles table, I would like to know to to filter users which role is admins.

like image 378
Chan Avatar asked Jan 27 '14 10:01

Chan


People also ask

What is polymorphic relationship in laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is all () in laravel?

all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.

What is eager loading in laravel?

Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.


1 Answers

This should give you all users who are admins.

$users = User::whereHas('roles', function($q) {
    $q->where('name', '=', 'admins');
})->get();

You can see more information on the has() method at http://laravel.com/docs/eloquent#querying-relations

like image 82
user1669496 Avatar answered Sep 27 '22 19:09

user1669496