Pagination for search results laravel 5.8

skipperhoa profile image Nguyễn Thanh Hòa ・2 min read

Information search in website using Laravel 5.8, Today, I'm share example simple pagination for search results in Laravel 5.8
Okay, youn can install laravel 5.8 version

composer create-project --prefer-dist laravel/laravel blog "5.8.*"

After then, you need create controller , you run command the following

php artisan make:controller SearchController --resource

SearchController.php file in directory App/Http/Controller, you open file and pass the following code

public function index(Request $request)
        $search =  $request->input('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('pages.search')->with('data',$users);

If user don't search, you get data all user in user table
if user search, you need using $search = $request->input('q'); get search value, after then append keyword $users->appends(['q' => $search]);

Ok, you to resources/views/pages directory create search.blade.php file, aften then you pass the following code

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <form action="">
                <h2>Search content in database using Laravel</h2>
                <div class="form-group">
                    <input type="text" name="q" placeholder="Search...!" class="form-control"/>
                    <input type="submit" class="btn btn-primary" value="Search"/>
        <div class="col-md-10">
            <table class="table">
                @foreach($data as $user)

            {{ $data->links() }}

Configuration Route in laravel, open web.php in routes/web.php directory


Test Paginated data with Search functionality in Laravel
php artisan serve
pagination for search results in laravel 5.8 - hoanguyenit.com
pagination for search results in laravel 5.8 - hoanguyenit.com

Post:Pagination for search results in Laravel 5.8
or more posts


Editor guide