Home >Backend Development >PHP Tutorial >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:
The repo class looks like below:
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
Then, send your model object to resource and format/manipulate your data as per requirement given below:
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:
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!….” ?>
The above is the detailed content of Laravel Resource or Customized Repo?. For more information, please follow other related articles on the PHP Chinese website!