简体   繁体   中英

Load time is very slow in API while fetching data in Laravel

I am using a simple query to list all the users in Laravel.

This is the query that I am using in Eloquent:

$user = User::find(1);

I get all the required data, but the time to get is more than 1.3 Second. While using the same in Doctrine loads the data in 300 ms.

Is there any issue of Eloquent in Laravel???

This may help someone who is facing this kind of problems. I've had similar issues with a lumen api backend. My lumen api took about 30-35 seconds to return ~1500 data and it took about 1.2 seconds using raw php on a shared hosting.

I searched for hours to find the issue, but found nothing. stirredo's answer gave me the idea to measure the time for executing my queries. The execution time showed that there was nothing wrong with the eloquent methods, rather the issue was inside the return statement. The tutorial I followed for creating the api used something like this-

return response()->json([$data]);

I replaced this with-

return json_encode($data);

And this simple change improved my response time from ~30 seconds to ~2.5 seconds. May be the json() method just iterates the data over and over for generating the json, which in turn creates a huge delay in response. So this might be helpful if any newbies like me are trying to solve delayed response issues with laravel/lumen. Reference for json() and json_encode() .

Go to [Your project dir]->laravel->app->config.php and change

'url' => '127.0.0.1' instead of localhost and see if that makes any difference.

If that doesn't work you can install Clockwork for laravel which will provide you with a timeline of whats taking so long.

Here's an example of the timeline I am talking about:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM