Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

php - romove obj from query laravel obj['pivot']

my query, I'm using laravel permission spatie. because I need to show the data it's will return the same format. and don't need to show pivot. if you see, the pivot is into employes->user->roles->pivote

public function index()
{
    $resp = Employes::where('estado', 1)
    ->with('user.roles:id,name')
    ->get();

    return  response()->json($resp);
}

Response

 [
   {
      "employ":"Juan",
      "age":21,
      "user":{
         "id":5,
         "name":"mario maradionio",
         "email":"[email protected]",
         "tipo_usuario":null,
         "roles":[
            {
               "id":1,
               "name":"root",
               "pivot":{
                  "model_id":5,
                  "role_id":1,
                  "model_type":"App\User"
               }
            },
            {
               "id":2,
               "name":"Alumno",
               "pivot":{
                  "model_id":5,
                  "role_id":2,
                  "model_type":"App\User"
               }
            },
            {
               "id":3,
               "name":"Encargado",
               "pivot":{
                  "model_id":5,
                  "role_id":3,
                  "model_type":"App\User"
               }
            }
         ]
      }
   ]

Model use SpatiePermissionTraitsHasRoles;

class User extends Authenticatable
{   
    use Notifiable;
    use HasRoles;
}

Using collection it not show the roles, just show one role and de name of role is null

[
            'id'         => $this->id,
            'employe'       => $this->name,
            'user' => [
               'id' => $this->id,
               'name' => $this->name,
               'roles' => [
                    'id' => $this->id,
                    'name' => $this->name
               ]
            ]
        ];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

add hidden attributes in your Role.php Model

create a Role.php and extends then SpatiePermissionModelsRole

<?php

namespace AppModels;

use SpatiePermissionModelsRole as BaseRole;

class Role extends BaseRole
{
    use HasFactory;

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'pivot'
    ];

}

ref link https://laravel.com/docs/8.x/eloquent-serialization#hiding-attributes-from-json


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...