Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between whereOr and orWhere in laravel

I have used whereOr and orWhere in my code in Laravel both works but at times gives different result

$user_query = User::select( 'users.id', 'users.username','users.first_name','users.last_name', 'users.photo' )
                    ->where('users.status',1)
                    ->where('users.id','!=',$id)
                    ->where('users.username','like','%'.$searchkey.'%')
                    ->orWhere('users.first_name','like','%'.$searchkey.'%')
                    ->orwhere('users.last_name','like','%'.$searchkey.'%')->get();

                    // ->whereOr('users.first_name','like','%'.$searchkey.'%')
                    // ->whereOr('users.last_name','like','%'.$searchkey.'%')->get();

What's the difference between whereOr and orWhere

like image 234
Ronser Avatar asked Dec 20 '14 09:12

Ronser


1 Answers

They both can do the same. But not really, since you're using whereOr wrong. whereOr is a dynamic where. They are described a bit more in depth in this blogpost

With dynamic wheres, the condition is defined not only parameters but by the method name itself. Here's an example:

->whereAge(18);

it could be translated into

->where('age', '=', 18);

This is done with the __call() function which then calls dynamicWhere(). This method then decodes the method name you called and saved that info as a where condition.

Now with whereOr you would actually have to call it like:

->whereAgeOrGender(18, 'male');

This means it gives you an easy syntax but is much less flexible than "real" wheres. For example it will always use the = operator. So it's definitely not suitable for your case.

like image 119
lukasgeiter Avatar answered Sep 30 '22 15:09

lukasgeiter