API Resources in Laravel convert Eloquent models and collections into JSON. This ensures consistent and structured API responses. They make it easier to customize the structure of the data returned by your application.
API Resources were introduced to aid API development in Laravel. They give developers flexibility in displaying data in JSON responses.
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);
}