Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :
InvestmentNovel

Latest Programming Tutorial Blog

Laravel Column Sorting With Pagination Tutorial With Example

/
/
/
281 Views

Hello developers, In this example, I will demonstrate to you how to do Laravel Column Sorting With Pagination Tutorial With Example. We will use kyslik/column-sortable package for column sorting and pagination in a laravel application. This is a very natural way to get links on the column headings in the table to sort the table data. You can sort the data based on a particular column either in ascending or descending order. By default, It will use the default font classes of Font Awesome to display the icons for sorting orders.

Laravel Column Sorting With Pagination Tutorial With Example

We are going to Configure Laravel Project.

#1: Download Laravel Project

Establish  Laravel Project by the typing following command.

composer create-project --prefer-dist laravel/laravel laravelcolumnsorting    

#2: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelcolumnsorting
DB_USERNAME=root
DB_PASSWORD=

#3: Install kyslik/column-sortable Package

First, install the kyslik/column-sortable package via the Composer package manager.

composer require kyslik/column-sortable

Let’s Add ServiceProvider in config/app.php

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

Publish the default configuration file by the following command:

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

#4: Build Model and Migration File

php artisan make:model Sharemarket -m

It will create a Sharemarket.php file and also create a create_sharemarkets_table.php  migration file.

//create_sharemarkets_table

public function up()
    {
        Schema::create('sharemarkets', function (Blueprint $table) {
            $table->increments('id');
            $table->string('companyname');
            $table->integer('price');
            $table->timestamps();
        });
    }

Save and run.

php artisan migrate

#5: Create a View File.

Create a file in resources/views/sharemarket.blade.php and put this following code in it.

<!-- sharemarket.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Column Sorting With Pagination Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    </head>
  <body>
    <div class="container">
      <h2>Laravel Column Sorting With Pagination Tutorial With Example</h2><br/>
      <form method="post" action="{{url('/sharemarket/store')}}">
        @csrf
        <div class="form-group row">
            <label for="name" class="col-md-4 col-form-label text-md-right">Company Name:</label>
            <div class="col-md-2">
                <input id="companyname" type="text" class="form-control" name="companyname">
            </div>
        </div>
        <div class="form-group row">
            <label for="country" class="col-md-4 col-form-label text-md-right">Price:</label>
            <div class="col-md-2">
                <input id="price" type="text" class="form-control" name="price">
            </div>
        </div>
      <div class=" form-group row">
          <div class="col-md-4"></div>
          <div class="col-md-2">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

#6: Create one controller

$ php artisan make:controller SharemarketController

It will build a controller file called SharemarketController.php.

//SharemarketController.php

public function create()
    {
        return view('sharemarket');
    }

#7: Define Route

We register all route in a web.php file.

Route::get('/sharemarket','SharemarketController@create');
Route::post('/sharemarket/store','SharemarketController@store');
Route::get('/sharemarket/index','SharemarketController@displayStock');

Laravel Column Sorting With Pagination Example

#8: Store data to the database

Next, we are set to fill in store () method with the logic to store data to the database.

//SharemarketController.php

use App\Sharemarket;

public function store(Request $request)
    {
        $stock = new Sharemarket();
        $stock->companyname = $request->get('companyname');
        $stock->price = $request->get('price');
        $stock->save();
        return redirect('/sharemarket/index')->with('success', 'Stock has been added');
    }

#9: Define a sortable trait in the model file

We have already created a model file called Sharemarket.php. Add following code in the model file.

//Sharemarket.php

<?php

namespace App;

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


class Sharemarket extends Model
{
    use Sortable;

    public $sortable = ['id','companyname','price','created_at','updated_at'];
}

Here we first include Sortable in the model file. Next, define an array called $sortable. This array includes fields like id,companyname, price,created_at,updated_at, which we have sorted later.

#10: Retrieve data from the database

Pass data to the view file first we create a displayStock() function in Controller to pass data to the view file.

//SharemarketController.php

public function displayStock()
    {
        $stocks = Sharemarket::sortable()->paginate(5);
        return view('index',compact('stocks'));
    }

Now, create a view file to display the data.

Create a file in resources/views/index.blade.php and placed this following code in it.

<!-- index.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index Page</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
   </head>
  <body>
    <div class="container">
    <br />
      @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
      @endif
     <h2>Index Page</h2>
    <table class="table table-bordered">
    <thead>
      <tr>
        <th>@sortablelink('id')</th>
        <th>@sortablelink('companyname')</th>
        <th>@sortablelink('price')</th>
        <th>@sortablelink('created_at')</th>
        <th>@sortablelink('updated_at')</th>
      </tr>
    </thead>
    <tbody>
      
      @foreach($stocks as $stock)
      <tr>
        <td>{{$stock->id}}</td>
        <td>{{$stock->companyname}}</td>
        <td>{{$stock->price}}</td>
        <td>{{$stock->created_at}}</td>
        <td>{{$stock->updated_at}}</td>
          </form>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>
  {!! $stocks->appends(\Request::except('page'))->render() !!}
  </div>
  </body>
</html>

Pagination and Column Sorting in Laravel

At last, our Laravel Column Sorting With Pagination Tutorial With Example is over.

  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest

1 Comments

  1. Hey there, great tutorial, however, I was hoping to see how you retrieve data and sort by column name. For instance, say I have a column named subject and I want to display in a div all records with a column name with the word “lambo”.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This div height required for enabling the sticky sidebar