Laravel 8 – Column sorting with pagination example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
Column sorting with pagination example

Hello Dev’s, I always try to find something new in my article for laravel developers. So today I will share with you how to column sorting with pagination example. Now We will sort our table with pagination in our laravel application. So we can do it column sorting by using kyslik/column-sortable composer package in laravel.

In laravel kyslik/column-sortable package provide us a simple sorting function and provide us default icon in this package. So they are provide us sortable() helper for query builder.

Now here i will give you a very short and simple example, so we can easily understand and customize as we want. Then after end of the tutorial we will get a layout as like as bellow and also easily sorting with each field. So let’s start and just follow.

Step 1 : Install Laravel Application

Now in this step we can install laravel application by using bellow command.by using Bellow command install Laravel 8 application.

composer create-project --prefer-dist laravel/laravel blog
Step 2: Install kyslik/column-sortable Package

Now in step 2 we will use bellow command to install our kyslik/column-sortable package. So open your terminal and then run bellow command.

composer require kyslik/column-sortable

After the successfully install package then after need to open config/app.php file and add service provider and alias.

config/app.php

'providers' => [
	....
	Kyslik\ColumnSortable\ColumnSortableServiceProvider::class,
]
.....

Suo we can publish the default configuration file by following command.

php artisan vendor:publish --provider="Kyslik\ColumnSortable\ColumnSortableServiceProvider" --tag="config"

Now after run above configuration command, we will find a file columnsortable.php in config folder. So we can simply change default configuration.

Step 3: Create Product Table and Model

Now in this step, we will create migration for products table by using laravel 8 php artisan command, So just fire bellow command.

php artisan make:migration create_products_table

Now need to Run this command after you will find migration file at database/migrations and we can put the bellow code in products table.

database/migrations/2014_10_12_000000_create_products_table.php

<?php


use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;


class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('price');
            $table->text('details');
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

After Migrate table after we can create Product model file.Now in this model you have to also add sortable facade. So just put bellow content in Product.php file:

app/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Kyslik\ColumnSortable\Sortable;

class Product extends Model
{
	use Sortable;

    protected $fillable = [ 'name', 'price','details' ];

	public $sortable = ['id', 'name', 'price','details', 'created_at', 'updated_at'];
}
Step 4: Add Route

Now in this step, we can create route for listing products lists. So just open your routes/web.php file and then add following route.

routes/web.php

Route::get('myproducts', 'ProductController@index');
Step 5: Create ProductController Controller

Now in this step, You will create new controller Product Controller in this file at path app/Http/Controllers/ProductController.php. So this controller will manage all listing products and sorting helper, so then put bellow content in controller file:.

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Product;

class ProductController extends Controller
{
    /**
     * Display the products dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::sortable()->paginate(5);
        return view('products',compact('products'));
    }

}
Step 6: Create products View File

Now in this step, we can create our view file for layout and we will write design code here and put following code.

resources/views/products.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 6 - Column sorting with pagination example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <h3 class="text-center">Laravel 6 - Column sorting with pagination example</h3>
    <table class="table table-bordered">
        <tr>
            <th width="80px">@sortablelink('id')</th>
            <th>@sortablelink('name')</th>
            <th>@sortablelink('price')</th>
            <th>@sortablelink('details')</th>
            <th>@sortablelink('created_at')</th>
        </tr>
        @if($products->count())
            @foreach($products as $key => $product)
                <tr>
                    <td>{{ $product->id }}</td>
                    <td>{{ $product->name }}</td>
                    <td>{{ $product->price }}</td>
                    <td>{{ $product->details }}</td>
                    <td>{{ $product->created_at->format('d-m-Y') }}</td>
                </tr>
            @endforeach
        @endif
    </table>
    {!! $products->appends(\Request::except('page'))->render() !!}
</div>
</body>
</html>

That’s good ,finally we got full example, we just need to insert dummy records in our products table then after run our example by using bellow php artisan command.

php artisan serve

So now we can open bellow URL on our browser:

http://localhost:8000/myproducts

Read also : How To Set Bcc And Cc Mail Address In Laravel Mail?

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →