Multi-user search query with multiple Laravel columns

I am very new to Laravel, currently working with Laravel4. I am trying to add a multi-column search function in my project. I can make one request for a brief search query, but frankly, I have no idea how to make several columns of eloquent search query in laravel.I has two drop-down menus

1.Locatiom 2.blood group.

I want to find a user having a specific blood type for a specific location . Thus, the user selects location and blood types from these two drop-down menus at a time and click the search button.

In my database, I have two columns, one contains location , and the other contains the blood group of a specific user. Now, what should be the eloquent query for such a search?

+6
source share
2 answers

A simple where chain for each field that you need to execute to search:

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

You can simplify the work thanks to the areas:

 // 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 SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get(); 

Just a reasonable example, customize it to your needs.

+24
source

This is a great way, but I'm sure there is a mistake somewhere, since laravel will not allow you to access a non-static function, so instead of using SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get(); you can just use SomeModel::BloodGroup($bloodGroup)->Location($location)->get();

do not accept the value of searchBloodGroup, has been changed to BlooGroup, here is how you will use it for everyone else.

0
source

Source: https://habr.com/ru/post/974628/


All Articles