Home > Back-end >  Laravel ->with(") is there a way to use it with attributes?
Laravel ->with(") is there a way to use it with attributes?

Time:02-05

I've been using ->("with) for relationships when querying models like so...

 return Model::
            where('set_id', $request->set)
            ->without('set')
            ->with('user:id,first_name,last_name,profile_photo')
        ->get();

Which works great for a relationship:

public function user(){
   return $this->belongsTo(User::class, 'user_id');
}

But what about doing the same with an attribute?

public function getPermissionsAttribute(){
        $permissions = $this->permissions;
        $new = [];
        foreach($permissions as $p){
            $new[$p->permission] = true;
        }
        return json_encode($new);
    }

Is there a way to do this in laravel? As at the moment I'm getting the following error...

App\Models\User::permissions must return a relationship instance. (View: C:\Users\Nick\PhpstormProjects\laravel-vue\resources\views\index.blade.php)

I did have it in:

public $appends = [
        'full_name',
        'profile_photo_thumb',
        'permissions'
......... etc ............
    ];

But, the list was getting longer and I was sending out data to the front end that largely wasn't used, so was causing longer loading

CodePudding user response:

You can append accessor at Run Time to help you decide what data you want serialized in the response by calling append on your Eloquent Collection:

return $collection->append('attribute');

Or for multiple, you can pass an array:

return $collection->append(['attribute1', 'attribute2']);

Laravel 8.x Docs - Eloquent - Serialization - Append Values to JSON - Appending at Run Time append

CodePudding user response:

Try to get it by select function like this

return Model::where('set_id', $request->set)->with(['user' => function ($query) {
     $query->select('id','first_name','last_name','profile_photo');
}])
  •  Tags:  
  • Related