DEV Community

Cover image for Laravel Resource or Customized Repo?
zaman shovon
zaman shovon

Posted on

Laravel Resource or Customized Repo?

Earlier this week, when working with the Laravel Rest API, I encountered an annoyance in the form of a timeout error. It leads to end-user frustration with development concerns. Let me brief the total scenario:

I needed to load data from an external data source, filter it, then prepare it for a json return. The amount of data was not large, only around 10K in a single request. The main problem occurred when I tried to format them after retrieving and filtering them. So, i started to debug using following step:

  • Check the query is optimized and columns are indexed as well.

  • Make sure use of chunk method

  • Check the formatting repo doesn’t use any unnecessary method/reference/implementation/unused functions/external api calling.

All checks are done but still it shows Gateway Timeout Error as it exceeds more than 1 minute. The service class looks like below:

Formatting Repo<br>

The repo class looks like below:

Formatting Repo

In naked eye, It shouldn’t throw timeout error for 10K+ data processing and manipulating. We will discuss at the end why it happens(mayn’t be actual concrete reason but probable) and now discuss how i resolve it using Laravel Api Resource.


Its simple to implement. First, generate Laravel Api Resource from command line:

php artisan make:resource DataFormatterResource

Enter fullscreen mode Exit fullscreen mode

Then, send your model object to resource and format/manipulate your data as per requirement given below:

Service Layer for business logic

Formatting Resource

Surprisingly, It only took 3.7 seconds to response 😮!
I tried to dig out the real issue here and found some probable cases that mentioned on top to define at the end. The cases are given:

  1. Laravel API resources provide a consistent interface for accessing and manipulating data where i use repo with some dependency injection in it. This makes it easier to write efficient code and to avoid common performance bottlenecks.
  2. Laravel API resources are optimized for performance as they use caching and other techniques to improve the speed of data retrieval and processing where i only go for chunk of array raw formatting.
  3. Laravel API resources automatically serialize the results of database queries to JSON or XML, depending on the request headers. This saves you the hassle of having to write your own serialization code.

At most of my project’s services, I utilized repo or functional formatter at the service layer, but in this case, I had a difficulty where there may be other causes for this issue to occur.
What I wanted to emphasize is that Laravel Resources might come in handy in some tricky situations when working with models.

If you like this article leave a clap or comment. <?= “Happy coding!….” ?>

Top comments (0)