Reputation: 502
I'm trying to retrieve a model the following way:
_id: 1, // ====> The model (example: Message)
text: 'My message',
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
user: { // ====> The model in the relationship, in this case, the USER
_id: 2,
name: 'React Native',
avatar: 'https://facebook.github.io/react/img/logo_og.png',
},
How is it possible for me to achieve this with laravel?
My current code looks this way:
public function show($id){
$id = Group::where('id', $id)->first();
return response()->json([
'messages' => $id->messages,
]);
}
Upvotes: 0
Views: 355
Reputation: 10714
You should take a look to JSON resources : https://laravel.com/docs/7.x/eloquent-resources
You can write your resource like :
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Group extends JsonResource
{
/**
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'_id' => $this->id,
'text' => $this->text,
'createdAt' => $this->created_at,
// define the User resource too
'user' => UserResource::collection($this->users)
];
}
}
And then just use :
// use model binding here, it will retrieve your model from the ID
public function show(Group $group)
{
return new GroupResource($group);
}
Upvotes: 1