Sharan
Sharan

Reputation: 788

Laravel - orWhere causes wrong results

I have the following query

 Event::where('event_name', $event_id)
        ->orWhere('id', $event_id)->first();

The $event_id can be a alpha-numeric string (event_name) or an integer (id - primary key). The orWhere statement takes priority over the where statement everytime unless the orWhere statement fails.

For example, the following query gets an event with id = 601, eventhough there is an event that has an event_name = 601a35e0ebee30 with id = 1070.

 Event::where('event_name', "601a35e0ebee30")
        ->orWhere('id', "601a35e0ebee30")->first();
  1. Shouldn't the where statement take precedence over orWhere? Am I missing something?
  2. Also how come a alpha-numeric string work with the primary key (id) which is an unsigened integer?

P.S. When I use Event::find("601a35e0ebee30"), it returns an event with id of 601

Upvotes: 0

Views: 408

Answers (2)

ojoago
ojoago

Reputation: 81

use nested array Event::where([['event_name', $event_id]])->orWhere([['id', $event_id]])->first();it works for me

Upvotes: 0

Gautam G
Gautam G

Reputation: 1

Please try this one.

Event::where(function($query) use ($event_id){
   $query->where('event_name', $event_id);
   $query->orWhere('id', $event_id);
})->first();

Upvotes: -1

Related Questions