Laravel Basic | Laravel Pagination Example Tutorial
In this tutorial, I would like to help you with how to create simple pagination in the laravel application. I will write a simple code of the laravel pagination example and show you how to use it in the blade file with paginate() and link() function. I will explain to you how to set a custom path with pagination, how to append input parameters with pagination link etc.
We know pagination is a primary requirement of each and every project. so if you are a beginner with laravel then you must know how to use pagination in laravel 6 and what is another function can use with laravel pagination.
In this example, I will explain to you from scratch how to work with laravel pagination. so let’s follow the below tutorial for creating a simple example of pagination with laravel.
Step 1: Add Route
The first thing is we put one route in one for list users with pagination. So simply add both routes to your route file.
routes/web.php
Route::get('users', 'UserController@index');
Step 2: Create Controller
Same things as above for route, here we will add one new method for a route. index() will return users with pagination data, so let’s add bellow:
app/Http/Controllers/UserController.php
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\User;class UserController extends Controller{/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function index(){$data = User::paginate(10);return view('users',compact('data'));}}
Step 3: Create Blade File
In this step, you need to create users blade file and put below code with links() so it will generate pagination automatically. So let’s put it.
resources/views/users.blade.php
@extends($theme)@section('content')<table class="table table-bordered"><thead><tr><th>Name</th><th width="300px;">Action</th></tr></thead><tbody>@if(!empty($data) && $data->count())@foreach($data as $key => $value)<tr><td>{{ $value->name }}</td><td><button class="btn btn-danger">Delete</button></td></tr>@endforeach@else<tr><td colspan="10">There are no data.</td></tr>@endif</tbody></table>{!! $data->links() !!}@endsection
Now you can run and check this example. it is a very simple and basic example.
If you need advanced use of pagination then you can see below how to use it.
Pagination with appends parameter
{!! $data->appends(['sort' => 'votes'])->links() !!}
Pagination with appends request all parameters
{!! $data->appends(Request::all())->links() !!}
I hope it can help you….