简体   繁体   中英

Is it possible to select users with admin role or moderator in Laravel?

I need to select all users with admin or moderator role. But when I try this code $user = Role::with('users')->where('name', '=', 'admin')->orWhere('name', '=', 'moderator')->get(); it's order them by roles like this:

    Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => admin
                [users] => Array
                    (
                        [0] => Array
                            (
                                [id] => 1
                                [name] => admin
                                [pivot] => Array
                                    (
                                        [role_id] => 1
                                        [user_id] => 1
                                    )

                            )

                    )

            )

        [1] => Array
            (
                [id] => 2
                [name] => moderator
                [users] => Array
                    (
                        [0] => Array
                            (
                                [id] => 2
                                [name] => Moderator
                                [pivot] => Array
                                    (
                                        [role_id] => 2
                                        [user_id] => 2
                                    )

                            )
                    )

            )

    )

Is there any way to get all users in one array with role admin or moderator?

Yeah. Since you are looking for users based on their role, start from the user instead.

$users = User::with('roles')->whereHas('roles', function($q)
{
    $q->whereIn('name', ['admin', 'moderator']);
})->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM