Laravel API Resource Nested Relationships
Laravel provides a powerful feature called API resource that allows you to easily transform your model data into a JSON response. With nested relationships, you can include related models and their data within the main response, providing a more comprehensive JSON representation of your data.
Here’s an example to explain nested relationships in Laravel API resource:
// Assume we have three models: User, Post, and Comment
// User model
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
// Post model
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
// Comment model
class Comment extends Model
{
// ...
}
// Define the API resource for each model
// UserResource
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'posts' => PostResource::collection($this->posts) // Include related posts
];
}
}
// PostResource
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'comments' => CommentResource::collection($this->comments) // Include related comments
];
}
}
// CommentResource
class CommentResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'content' => $this->content,
];
}
}
// In your controller
public function show(User $user)
{
return new UserResource($user);
}
In the above example, we have three models: User, Post, and Comment. The User model has a one-to-many relationship with the Post model, and the Post model has a one-to-many relationship with the Comment model.
We define API resources for each model: UserResource, PostResource, and CommentResource. These resources define how the data should be transformed into a JSON response.
In the UserResource, we include the related posts by calling the PostResource::collection method and passing in the user’s posts. This will transform the posts into the desired JSON format.
Similarly, in the PostResource, we include the related comments by calling the CommentResource::collection method and passing in the post’s comments.
Finally, in the controller’s show method, we return a new instance of the UserResource, passing in the user. This will transform the user and its related posts into a JSON response.