Skip to content

Laravel API Resource transform model to JSON response

PHP Dasun Kalupahana 103 views

<?php

// php artisan make:resource PostResource
namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id'      => $this->id,
            'title'   => $this->title,
            'author'  => new UserResource($this->whenLoaded('author')),
            'created' => $this->created_at->toIso8601String(),
        ];
    }
}

// Controller
return PostResource::collection(Post::with('author')->paginate(15));

Controls exactly which fields your API returns, so you never leak columns by accident. whenLoaded includes a relation only if it was eager loaded, which avoids extra queries.

Learn more on the blog

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.