Laravel-datatables: Using orWhere query causes problem in the search.

Created on 12 Apr 2020  路  3Comments  路  Source: yajra/laravel-datatables

Summary of problem or feature request


I am using "orWhere" clause in my Laravel application where I build the datatable query. The results I get are perfect, but when I try to use the search it is messing up the results, no errors occur, but the results are not accurate at all.

Code snippet of problem

This is my query:

$data = Result::where(function($query) {
                                  $query->where('type', 'news');
                              })
                             ->orWhere(function($query) {
                                 $query->where('type', 'editorials')
                                       ->where('year', '>=', 2018);
                             })
                             ->select('results.*');

If I remove the orWhere clause, the search is fixed. The problem is not from the callback function it is from the orWhere. I am not sure how to fix this. Any suggestions will be appreciated.

System details

  • Ubuntu 16.04
  • PHP 7.2
  • Laravel 5.8.13
  • yajra/laravel-datatables-oracle: "^9.0"
question sql

All 3 comments

I think the prob is on your query. Maybe try to chain orWhere inside one closure instead.

$data = Result::where(function($query) {
                                  $query->where('type', 'news')
                             ->orWhere(function($query) {
                                 $query->where('type', 'editorials')
                                       ->where('year', '>=', 2018);
                             })
                             ->select('results.*');

Even if I make the query like this:

$data = Result::where('type', 'news')->orWhere('type', 'editorials')->select('results.*');

The search problem remains (the above query is just to test it). The orWhere clause causes the problem I think. The thing is I need orWhere clause so I can exclude all the editorials before 2018, so I have to use it.

I followed your suggestion. With a query such as this:

$data = Result::where(function($query) {
                        $query->where('type', 'news');
                        $query->orWhere(function($query_two) {
                           $query_two->where('type', 'editorials')
                                     ->where('year', '>=', 2018);
                           });
                     })
                     ->select('results.*');

So indeed the problem comes if orWhere is in the query. But if orWhere is in the callback, the problem disappears.

Thank you for the suggestion. Hope this also helps to someone else! :)

This helped me too, thank you.

Was this page helpful?
0 / 5 - 0 ratings