Step 1: Create an API Resource
First, generate a resource for your model. Let's use a Post model as an example.
php artisan make:resource PostResource
//This creates a PostResource.php file in App\Http\Resources.
Step 2: Define Data Structure in Resource
Open PostResource.php and define the data structure you want to return.
<?php
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->user->name,
'created_at' => $this->created_at->toDateString(),
];
}
}
Here, we’re only returning specific fields: id, title, content, author, and created_at.
Step 3: Use Resource in Controller
Return this resource from your controller to format the response.
use App\Http\Resources\PostResource;
use App\Models\Post;
class PostController extends Controller
{
public function show($id)
{
$post = Post::findOrFail($id);
return new PostResource($post);
}
}
Resulting JSON Response
When you call this API, you'll get a formatted JSON response:
{
"data": {
"id": 1,
"title": "Sample Post",
"content": "This is the content of the post.",
"author": "John Doe",
"created_at": "2024-10-26"
}
}
Laravel API Resources help keep API responses clean and structured, making it easier to manage what data gets sent to clients. Use them to control and format output effectively.