API Resources in Laravel provide a way to transform Eloquent models and collections into JSON responses, ensuring consistent and structured API responses. They simplify the process of customizing the structure of the data returned by your application.
API Resources were introduced to simplify API development in Laravel, providing developers with tools to control how data is presented in JSON responses.
toArray
Method: Define the structure of the JSON response in the toArray
method of the resource.To create an API Resource for a Post
model:
php artisan make:resource PostResource
In the generated class:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'author' => $this->author->name,
];
}
}
Use the resource in your controller:
use App\Http\Resources\PostResource;
public function show(Post $post)
{
return new PostResource($post);
}
This approach ensures that API responses are structured, maintainable, and consistent.