How to make resources more reusable in Laravel

how-to-make-resources-more-reusable-in-laravel

When working with Laravel API, we utilize resources to manage the process of returning collections in each response.

But, How can we do this with a single resource file to avoid messy file structures?

And how can we make our resources more reusable for each operation, especially in something like ( index & show ),

We can differentiate between inside responses using this route name,

So If we don’t want to show all attributes in the index, we can hide them from the index resource.

Here’s our example:

  • We defined our route in the api.php code:
Route::apiResource('/posts', ApiPostController::class, ['only' => ['index', 'show']]);
  • Now in our resource, We put a condition when the request coming from a route named posts.show:
        $routeShowPost = $request->routeIs('posts.show');

And here’s our PostResource, with the power of mergeWhen(), we can show or hide the attributes from the resource:



namespace AppHttpResources;

use IlluminateHttpResourcesJsonJsonResource;
use IlluminateSupportFacadesRoute;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        $routeShowPost = $request->routeIs('posts.show');

        return [
            'id' => $this->id,
            'title' => $this->title,
            'image' => $this->image,
            'created_at' => $this->created_at,
            $this->mergeWhen($routeShowPost, [
                'content' => $this->content,
                'comments' => CommentResource::collection($this->whenLoaded('comments'))
            ]),
            'user' => UserResource::make($this->whenLoaded('user')),
            'category' => GeneralResource::make($this->whenLoaded('category')),
            'tags' => GeneralResource::collection($this->whenLoaded('tags')),
        ];
    }
}

In our example, we show the post’s content and comments only when the route is posts.show.

Thanks for reading,

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
the-force-of-decision-rules:-applying-specific-and-global-risk-to-star-wars

The Force of Decision Rules: Applying Specific and Global Risk to Star Wars

Next Post
how-to-copy-table-data-easily-with-this-chrome-extension

How to copy table data easily with this Chrome Extension

Related Posts