Dmitry Malys
Dmitry Malys

Reputation: 1323

Laravel Eloquent loads slow

there is a lot of similar topics but couldn't find a solution for me. This query loads very slow.

public function getAllBids()
{

    return Bid::with('user', 'group')
        ->join('auct_lots', function ($join) {
            $join->on('bids.lot_id', '=', 'auct_lots.lot_id')
                    ->where('auct_lots.company', 'LIKE', '%' . request('brand') . '%')
                    ->where('auct_lots.model_name', 'LIKE', '%' . request('models') . '%')
                    ->where('auct_lots.grade_en', 'LIKE', '%' . request('carGrade') . '%')
                    ->where('auct_lots.auction_name', 'LIKE', '%' . request('auctions') . '%')
                    ->where('auct_lots.model_type_en', 'LIKE', '%' . request('chassis') . '%')
                    ->where('auct_lots.bid', 'LIKE', '%' . request('lots') . '%')
                    ->where('auct_lots.lot_date', 'LIKE', '%' . request('date') . '%');
        })
        ->orderBy('auct_lots.' . request('order_column'), request('order_type'))
        ->paginate(30);

}

I think the problem is that auct_lots has more than 40,000 records... But I'm not sure how to refactor this code to work faster.

Upvotes: 0

Views: 893

Answers (1)

Yash Joshi
Yash Joshi

Reputation: 36

When you are having large amount of data, it is better to use server side caching. This will improve performance very much faster.

Step 1: Create a Trait and write logic for store values in caching. Ex:

trait Student{
  public function storeStudentDataInCache(){
       $students = Cache::rememberForever('studentList', function () {
        return Student::
        with(['class', 'exams'])
        ->where('is_published', 1)->orderBy('display_sequence', 'ASC')->get();
        });
    return $students;
    }
}

Now in your controller call this method, this will return collection of data. So you do not need run sql queries all the time to get data. This method will run query only after one time. After that data will be stored in caching so it will get data's collection from caching text file.

Note: Whenever you update your data,please do not forget to delete this cache.

And you can also apply where condition for laravel collection or you can use filter method of collection to implement more filter logic.

Upvotes: 1

Related Questions