Rego Rego - 1 year ago 201
SQL Question

Laravel multiple column eloquent search query

i am very new in Laravel,currently working with Laravel4.I am trying to add a multiple column search functionality in my project.I can do single column eloquent search query,But honestly i have no idea how to do multiple column eloquent search query in laravel.I have two drop down menu

2.blood group.

i want to search an user having certain blood group against certain location.That is, user will select a location and blood group from those two drop down menu at a time and hit the search button.

In my database,i have two column, one contains the location and another contains the blood group of a certain user. Now,what should be the eloquent query for such a search?

Answer Source

Simply chain where for each field you need to search through:

// AND
$results = SomeModel::where('location', $location)->where('blood_group', $bloodGroup)->get();

// OR
$results = SomeModel::where('location', $location)->orWhere('blood_group', $bloodGroup)->get();

You can make it easier to work with thanks to the scopes:

// SomeModel class
public function scopeSearchLocation($query, $location)
  if ($location) $query->where('location', $location);

public function scopeSearchBloodGroup($query, $bloodGroup)
  if ($bloodGroup) $query->where('blood_group', $bloodGroup);

// then 

Just a sensible example, adjust it to your needs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download