I'm very new to Laravel also client side rendering.
The thing with Client Side Rendering is we have to be very careful while sending data to front-end.
I'm not sure how can I do it for nested relations. Also I don't want to do this at the query level instead filtering it afterwards.
Like,
$user = User::with('blogs.comments.user')->find(1);
I mean i can do
$user->only('id', 'name', 'blogs');
It will work but only on the first user layer not for relations.
Thank you so much for reading.. :)
CodePudding user response:
I recommend to use Laravel resources.
https://laravel.com/docs/9.x/eloquent-resources
From documentation;
php artisan make:resource UserResource
use App\Http\Resources\PostResource;
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'posts' => PostResource::collection($this->posts),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
CodePudding user response:
You Can archived that simply using WhereHas
$user = User::with('blogs.comments.user')
->whereHas('blogs',function($query)
{
$query->select('id','name')
->whereHas('comments',function($qu)
{
$qu->select('id','name')
->whereHas('user',function($q)
{
$q->select('id','name');
});
});
})
->find(1);