Laravel 9 pagination with search filter

Updated at 03-Mar-2022, By samar

Laravel 9 pagination with search filter

Good day, guys. In this post, we’ll look at how to solve the "Laravel 9 pagination with search filter" programming puzzle.

Sometimes we have to filter data from a table in Laravel using the search keyword provided by users. Here we provide search functionality with pagination in Laravel 9.
  • Pagination with search filter in Laravel 9

    //Run below command to make HomeController

    php artisan make:controller HomeController


    use App\Http\Controllers\HomeController;
    Route::any('/home', [HomeController::class, 'index'])->name('user');


    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Models\User;
    class HomeController extends Controller
        public function index(Request $request){
            $users = User::paginate(2);
            $search = $request->q;
                $users = User::where(function ($query) use ($search){
                    $query->where('name', 'like', '%'.$search.'%')
                        ->orWhere('email', 'like', '%'.$search.'%');
                $users->appends(['q' => $search]);
                $users = User::paginate(2);
            return view('home', compact('users'));


    <form action="{{ route('user') }}" method="POST">
        <input type="text" name="q" placeholder="search by user name and email..." />
        <button type="submit"> Search </button>
    <table class="table table-bordered">
                <th>First Name</th>
            @foreach($users as $user)
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
        {{ $users->links() }}

    You have to create a controller using php artisan make:controller HomeController.

    Define route in web.php

    Create controller method in HomeController class.

    You also have to create a blade file home.blade.php in resources/views directory. 


Back to code snippet queries related laravel