Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cskiwi's avatar

Making a laravel feed faster via better SQL fetch ?

Hi,

for a school project I've been making this feed. but I find it very slow. and I was thinking on forcing some more processing on the SQL part instead of processing it on the php side

I'm using the search thingy from nicolaslopezj . and that is fast as hell. So I'm olmost certain that it's the php code :)

And the algorithm isn't even great, so I could use another opinion/tips&tricks for the following code?


public function feed() { // pagination stuff $perPage = 15; $page = (Input::has( 'page' )? Input::get( 'page' ) : 1); $offset = ( ( $page - 1 ) * $perPage ); // feed start $feed = new Collection(); // start arrays $posts = new Collection(); $stories = new Collection(); $groups = Auth::user()->groups; // check if user has friends if (Auth::user()->friends()->count() != 0) { // get from good relationship $friendCollection = Auth::user()->friends()->Where( 'relationShipStatus', '>', '50' ); // get all posts $posts = Post::whereIn( 'user_id', $friendCollection->lists( 'id' ) )->orWhere( 'user_id', Auth::user()->id )->get(); // filter out where no group nor in story foreach ($posts as $index => $post) { if ($post->Stories()->count() > 0) { unset( $posts[$index] ); } if ($post->Group()->count() > 0) { unset( $posts[$index] ); } } // get those stories $stories = Story::whereIn( 'user_id', $friendCollection->lists( 'id' ) )->orWhere( 'user_id', Auth::user()->id )->get(); } // merge together $posts->isEmpty() ?: $feed = $feed->merge( $posts ); $stories->isEmpty() ?: $feed = $feed->merge( $stories ); $groups->isEmpty() ?: $feed = $feed->merge( $groups ); // sort by updated date $feed->isEmpty() ?: $feed = $feed->sortBy( 'updated_at' )->reverse(); // apply pagination $userFeed = new Paginator( $feed->slice( $offset, $perPage, true )->all(), $feed->count(), $page ); return $this->RespondWithPagination( $userFeed, $feed->count(), [ 'data' => FeedTransformer::transformCollection( $userFeed ) ] ); }

all models can be found here: https://gist.github.com/285082ae6005a77e2c1e.git

0 likes
5 replies
cskiwi's avatar

did some speed tests and with the code above 1 had an average of about 4200ms changed the get all posts to the following and the speed is decreased to 2800ms

// get all posts
      $posts = Post::has( 'Stories', '=', 0 )->has( 'Group', '=', 0 )->whereIn(
        'user_id', $friendCollection->lists( 'id' )
      )->orWhere( 'user_id', Auth::user()->id )->has( 'Stories', '=', 0 )->has( 'Group', '=', 0 )->get();
cskiwi's avatar

@malfait.robin

That is going to speed the process, but I think the fetch itself can have lot's of improvements.

cskiwi's avatar

@ajschmaltz How do you mean? And there are 3 differnt models that are being fetched so I've to sort them in group not by model

Please or to participate in this conversation.