when method in laravel

Laravel Eloquent when example

In this tutorial, I will give you an example of Laravel Eloquent when example, So you can easily apply it with your laravel 6, laravel 7, laravel 8, and laravel 9 applications.

First, what we’re doing here, This is the example :

Laravel Eloquent when example
Laravel Eloquent when Method search filter

Laravel Eloquent when Method example

I will tell you there’s a (much) better way. Easily readable and simple. Meet when() method.

Laravel eloquent added a new function called when(), using when() you can ignore to write manually if conditional statement. I will give you some examples of how to use it when and how to write if condition with an eloquent query builder. you can also use when() with laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 versions.

Search and Filter data without using if, else in Laravel using the When Method :-

I am using 3 database tables to perform this search filter.

  • Users
  • Categories
  • Posts
Laravel Eloquent when example filter

Filter data using when in laravel

advance search without using if else in laravel

Create a Controller :

php artisan make:controller SearchController

routes\web.php :

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

#When Method Example in Laravel
Route::get('/search', [SearchController::class, 'index']);
Route::post('/search-filter', [SearchController::class, 'searchFilter'])->name('search.filter');

app\Http\Controllers\SearchController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Post;
use App\Models\User;

class SearchController extends Controller
{
    public function index(){
        $categories = Category::orderBy('cat_name')->get();
        $users = User::select('id','name')->get();
        return view('search.index',compact('categories','users'));
    }

    public function searchFilter(Request $request){
         $posts = Post::select("*")
        ->when($request->author, function ($query) use ($request) {
            $query->where('user_id', $request->author);
        })
        ->when($request->category, function ($query) use ($request) {
            $query->where('category_id', $request->category);
        })
        ->when($request->title, function ($query) use ($request) {
            $query->where('title', 'LIKE', '%' . $request->title .'%');
        })
        ->get();
       dd($posts); 
    }
}

resources\views\search\index.blade.php :

<section class="search-sec">
    <div class="container">
         <div class="row">
                <div class="col-lg-12">
                    <form method="POST" action="{{route('search.filter')}}">
                    @csrf
                    <div class="row">
                        <div class="col-lg-3 col-md-3 col-sm-12 p-0">
                            <input type="text" class="form-control search-slt" placeholder="Enter Title" name="title">
                        </div>
                        <div class="col-lg-3 col-md-3 col-sm-12 p-0">
                            <select class="form-control search-slt" name="category">
                                <option value="" selected>Select Category</option>
                                @foreach ($categories as $category)
                                <option value="{{ $category->id }}">{{ $category->cat_name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-3 col-md-3 col-sm-12 p-0">
                            <select class="form-control search-slt" name="author">
                                <option value="" selected>Select Author</option>
                                @foreach ($users as $user)
                                <option value="{{ $user->id }}">{{ $user->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-3 col-md-3 col-sm-12 p-0">
                            <button type="submit" class="btn btn-danger wrn-btn">Search</button>
                        </div>
                    </div>
                    </form>
                </div>
            </div>
    </div>
</section>

Related Article :- Laravel Ajax autocomplete search.

Run Application :

http://127.0.0.1:8000/search

Output:-

Search By Keyword (Title) :-

Laravel Eloquent when example filter
filter data by keyword using when method in laravel

Search By Category :-

search by category using when method in laravel
filter data by category using when method in laravel

Search By Category and Author :-

search by category and author using when method in laravel
filter data by category and author using when method in laravel

Search By Keyword, Category and Author :-

search by keyword, category and title using when method in laravel
filter data by keyword, category and author using when method in laravel

In this article, we learned “Filter data using the When method in Laravel Eloquent without using any if-else conditions”, I hope this article will help you with your Laravel application Project.

Read also :- Pass data to all views in Laravel 8.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com