📅  最后修改于: 2023-12-03 14:47:31.614000             🧑  作者: Mango
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.
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);
}
}
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);
}
}
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".
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.