问题描述
我的查询,我正在使用 laravel 权限 spatie。因为我需要显示它会返回相同格式的数据。并且不需要显示枢轴。 如果你看到,支点是员工->用户->角色->支点
public function index()
{
$resp = Employes::where('estado',1)
->with('user.roles:id,name')
->get();
return response()->json($resp);
}
[
{
"employ":"Juan","age":21,"user":{
"id":5,"name":"mario maradionio","email":"empleado@gmail.com","tipo_usuario":null,"roles":[
{
"id":1,"name":"root","pivot":{
"model_id":5,"role_id":1,"model_type":"App\\User"
}
},{
"id":2,"name":"Alumno","role_id":2,{
"id":3,"name":"Encargado","role_id":3,"model_type":"App\\User"
}
}
]
}
]
模型 使用 Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
}
[
'id' => $this->id,'employe' => $this->name,'user' => [
'id' => $this->id,'name' => $this->name,'roles' => [
'id' => $this->id,'name' => $this->name
]
]
];
解决方法
在您的 Role.php
模型中添加隐藏属性
创建一个 Role.php
并扩展然后 Spatie\Permission\Models\Role
<?php
namespace App\Models;
use Spatie\Permission\Models\Role as BaseRole;
class Role extends BaseRole
{
use HasFactory;
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'pivot'
];
}
参考链接 https://laravel.com/docs/8.x/eloquent-serialization#hiding-attributes-from-json
,您应该创建一个 Resource 类并返回它。
public function index()
{
$employees = Employes::where('estado',1)
->with('user.roles')
->get();
return EmployeeResource::collection($employees);
}
您可以参考创建资源的文档:https://laravel.com/docs/8.x/eloquent-resources