Hello guys in this tutorial i will show you how we can filter data using laravel eloquent when condition. If we use eloquent when condition then no need to use if else. It reduces our code and code looks pretty readable.
How to use if condition in laravel query is the topic to solve that. But we can do same staff without using if else condition in laravel eloquent query. When gives us amazing easy condition handling feature.
Laravel takes two parameter. One is boolean and other is a callback function by their respective boolean value. I am going to simply replace this if else condition in laravel query with when condition to do same staff.
When()
Laravel Eloquent when
method will execute the given callback when the first argument given to the method evaluates to true
:
$collection = collect([1, 2, 3]);
$collection->when(true, function ($collection) {
return $collection->push(4);
});
$collection->when(false, function ($collection) {
return $collection->push(5);
});
$collection->all();
Let's see using this when condition how we can filter our requested data. So in this example i also going to show you using eloquent when condition we can filter our data where exists multiple request and we can easily handle it using when condition.
Using when condition we can easily do laravel filter data from dropdown. So let's see the example that how we can filter our data using when condition.
Step 1: Create Dropdown
We are going to see that how to filter data in laravel using when condition with dropdown. So create a dropdown list to send server request.
doctor.blade.php
Step 2: Create Route
We have to create route. In this step paste this code in your web.php
routes\web.php
Route::namespace('Frontend\Doctor')->group(function(){
Route::get('/', 'HomeController@index')->name('doctor.list');
});
Step 3: Create Controller
In this step we will create our @index method to filterized our requested data from database. Se paste this below code in indexController
App\Http\Controllers\Frontend\Doctor\IndexController.php
namespace App\Http\Controllers\Frontend\Doctor;
use App\Models\Doctor;
use Illuminate\Http\Request;
use App\Repository\Doctor\IDoctor;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
public function index(Doctor $doctor, Request $request)
{
$doctor = $doctor->when($request->country, function($doctor) use($request){
return $doctor->where('country_id',$request->country);
})
->when($request->designation, function($doctor) use($request){
return $doctor->where('designation_id',$request->designation);
});
return view('welcome',
[
'doctors' => $doctor,
'select_doctor' => $request->country,
'selected_designation' => $request->designation
]
);
}
}
Recommended : Advanced Search Filter using Dropdown in Laravel
Now if you select any select box data any hit filter button then it will fetch only those filter data. Hope it can help you devs.
#laravel #laravel-8x #laravel-eloquent #eloquent-tips