Reysa's avatar
Level 1

Multiple filtering data with Model::query()

Hello , I'm so so sorry for title if it's bad I couldn't find better one :D

My problem is I want to show a data from db but with multiple filtering

I'm doing it with model::query() now but I have a big problem

this is my code:

$qry = Raid::query();
$first = $qry->whereIn('status', [1,4])->where('type_id', 1)->paginate(20, ['*'], 'first');
$second = $qry->whereIn('status', [1,4])->where('type_id', 2)->paginate(20, ['*'], 'second');

problem is $second is not showing the correct data because in the $first line , it applies the filter so the second one is using first one too

I have to show multiple data in one page and I have pagination for all of them so I have to paginate them one by one

Is there anyway to do it without calling Model multiple times? because it's 12 different variable at max so it's not possible to call eloquent 12 time :D

Thanks in advance

0 likes
9 replies
aliabdm's avatar

I dont know if I got you right , but it looks like you need to use when() or an if to choose which query to call

viktorivanov's avatar

@reysa it is because you are having one query instance $qry and each where clause is applied to it.

What you can do is create multiple instances, eg


$first = Raid::query()->whereIn('status', [1,4])->where('type_id', 1)->paginate(20, ['*'], 'first');
$second = Raid::query()->whereIn('status', [1,4])->where('type_id', 2)->paginate(20, ['*'], 'second');
Reysa's avatar
Level 1

@viktorivanov that's the point , I don't want to call a raid query 12 times on each load :D

Sinnbeck's avatar

@Reysa that's how the query builder works. One for each database call

Whats the problem with writing it for each one? And you can leave out the query() part if you want

Sinnbeck's avatar

@Reysa it might. But if you really need 12 queries then you need 12 instances of the query builder. Maybe the question is rather why you need that many queries for a single page?

Reysa's avatar
Level 1

@Sinnbeck isn't there anyway to get the data with static wheres and then filter it by type one by one?

Reysa's avatar
Level 1

@Sinnbeck I'm showing a list of data and filtering them in different bootstrap tabs that's why I'm filtering them by type and status , client wants it in a single-page so I have to show them all in one page

Sinnbeck's avatar

@Reysa if you don't need pagination then maybe yes. But it might be even slower. If you want to try it out I suggest you try writing that huge single query directly in your database manager and then transfer it to laravel.

Did you try just running the queries and see what kind of speed you are getting? If you have an index on type_id it will probably be quite fast

Please or to participate in this conversation.