📜  spartie all user with role get laravel - PHP (1)

📅  最后修改于: 2023-12-03 14:47:31.614000             🧑  作者: Mango

Topic: How to get all users with a specific role in Laravel

Laravel provides a convenient way to retrieve all users with a specific role. In this tutorial, we will show you how to get all users with a role in Laravel.

Step 1: Define Role Model

First, you need to define a Role model. A Role model is used to store the roles within the database, and it will be used to relate roles to users.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = [
        'name',
        'description',
    ];

    public function users()
    {
        return $this->hasMany(User::class);
    }
}
Step 2: Define User Model

Next, you need to define a User model. You can use Laravel's default User model, or you can create your own. In either case, you should ensure that the User model has a relationship with the Role model.

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    public function role()
    {
        return $this->belongsTo(Role::class);
    }
}
Step 3: Get All Users with a Role

You can get all users with a particular role by using Laravel's Eloquent ORM. We will demonstrate how to retrieve all users with the "admin" role.

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

This code fragment will retrieve all users whose related Role model has a "name" field equal to "admin".

Conclusion

In this tutorial, we have shown you how to get all users with a role in Laravel. By creating a Role model and a User model with a relationship between them, you can easily retrieve all users with a particular role using Eloquent ORM.