How to create CRUD, search, sort and pagination with Laravel 5.5

Published Date: 25-Nov-2017 | Tags: Laravel 5.5  Bootstrap 4  CRUD  

This tutorial I want to show you how to create a complete CRUD (Create, Read, Update, Delete), search, sort and pagination operations with Laravel 5.5

Suppose that your server is running on port 80 and your project folder is /demo.

Note

  • I use laravelcollective to create form. So please install laravelcollective if you not yet install it. You can visit here for the installation guide.
  • I use bootstrap 4 for my UI, so please check bootstrap if you are new to bootstrap.

 

Step 1: Create Database Table

 Create table customers with structure as below.

customer table structure

 

Step 2: Database Configuration

Edit this file /demo/.env and update your database name, username and password.

Suppose that your database name is demo, username is root, and password is empty.

laravel db config

 

Step 3: Add Route

Add these lines to file /demo/routes/web.php.

Route::group(['prefix' => 'laravel-crud-search-sort'], function () {
    Route::get('/', 'Crud2Controller@index');
    Route::match(['get', 'post'], 'create', 'Crud2Controller@create');
    Route::match(['get', 'put'], 'update/{id}', 'Crud2Controller@update');
    Route::delete('delete/{id}', 'Crud2Controller@delete');
});

 

Step 4: Create Model

Create model file Customer.php in /demo/app.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{

}

 

Step 5: Create View

Create layout view file default.blade.php in /demo/resources/views/layout. (create folder layout if it does not exist) 

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
@yield('head')
<!-- Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    @yield('css')
</head>
<body style="padding-top: 100px;padding-bottom: 50px;background: whitesmoke">
<nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-info">
    <a class="navbar-brand" target="_blank" href="http://www.codovel.com">CODOVEL.COM</a>
    @yield('nav')
</nav>
@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
@yield('js')
</body>
</html>

 

Create view file index.blade.php in /demo/resources/views/crud_2. (create folder crud_2 if it does not exist)

@extends('layout.default')
@section('css')
    <style>
        a, a:hover {
            color: white;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="float-right">
            <a href="{{url('laravel-crud-search-sort/create')}}" class="btn btn-primary">New</a>
        </div>
        <h1 style="font-size: 2.2rem">Customers List (Laravel CRUD, Search, Sort Example)</h1>
        <hr/>
        {!! Form::open(['method'=>'get']) !!}
        <div class="row">
            <div class="col-sm-4 form-group">
                {!! Form::select('gender',['-1'=>'Select Gender','Male'=>'Male','Female'=>'Female'],null,['class'=>'form-control','onChange'=>'form.submit()']) !!}
            </div>
            <div class="col-sm-5 form-group">
                <div class="input-group">
                    <input class="form-control" id="search"
                           value="{{ request('search') }}"
                           placeholder="Search name" name="search"
                           type="text" id="search"/>
                    <div class="input-group-btn">
                        <button type="submit" class="btn btn-warning"
                        >
                            Search
                        </button>
                    </div>
                </div>
            </div>
            <input type="hidden" value="{{request('field')}}" name="field"/>
            <input type="hidden" value="{{request('sort')}}" name="sort"/>
        </div>
        {!! Form::close() !!}
        <table class="table table-bordered bg-light">
            <thead class="bg-dark" style="color: white">
            <tr>
                <th width="60px" style="vertical-align: middle;text-align: center">No</th>
                <th style="vertical-align: middle">
                    <a href="{{url('laravel-crud-search-sort')}}?search={{request('search')}}&gender={{request('gender')}}&field=name&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
                        Name
                    </a>
                    {{request('field','name')=='name'?(request('sort','asc')=='asc'?'&#9652;':'&#9662;'):''}}
                </th>
                <th style="vertical-align: middle">
                    <a href="{{url('laravel-crud-search-sort')}}?search={{request('search')}}&gender={{request('gender')}}&field=gender&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
                        Gender
                    </a>
                    {{request('field')=='gender'?(request('sort','asc')=='asc'?'&#9652;':'&#9662;'):''}}
                </th>
                <th style="vertical-align: middle">
                    <a href="{{url('laravel-crud-search-sort')}}?search={{request('search')}}&gender={{request('gender')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
                        Email
                    </a>
                    {{request('field')=='email'?(request('sort','asc')=='asc'?'&#9652;':'&#9662;'):''}}
                </th>
                <th width="130px" style="vertical-align: middle">Action</th>
            </tr>
            </thead>
            <tbody>
            @php
                $i=1;
            @endphp
            @foreach($customers as $customer)
                <tr>
                    <th style="vertical-align: middle;text-align: center">{{$i++}}</th>
                    <td style="vertical-align: middle">{{ $customer->name }}</td>
                    <td style="vertical-align: middle">{{ $customer->gender }}</td>
                    <td style="vertical-align: middle">{{$customer->email}}</td>
                    <td style="vertical-align: middle" align="center">
                        <form id="frm_{{$customer->id}}"
                              action="{{url('laravel-crud-search-sort/delete/'.$customer->id)}}"
                              method="post" style="padding-bottom: 0px;margin-bottom: 0px">
                            <a class="btn btn-primary btn-sm" title="Edit"
                               href="{{url('laravel-crud-search-sort/update/'.$customer->id)}}">
                                Edit</a>
                            <input type="hidden" name="_method" value="delete"/>
                            {{csrf_field()}}
                            <a class="btn btn-danger btn-sm" title="Delete"
                               href="javascript:if(confirm('Are you sure want to delete?')) $('#frm_{{$customer->id}}').submit()">
                                Delete
                            </a>
                        </form>
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
        <nav>
            <ul class="pagination justify-content-end">
                {{$customers->links('vendor.pagination.bootstrap-4')}}
            </ul>
        </nav>
    </div>
@endsection

Note: The above view I use boostrap 4 pagination. So please export laravel built-in pagination files by going to terminal or command prompt (for window users), navigate to your project directory (/demo), and run this command

php artisan vendor:publish --tag=laravel-pagination

The above command will place all pagination views in the /resources/views/vendor/pagination. You can customize and use the one you need.

Create view file form.blade.php in /demo/resources/views/crud_2. (create folder crud_2 if it does not exist)

@extends('layout.default')
@section('css')
    <style>
        .form-group.required label:after {
            content: " *";
            color: red;
            font-weight: bold;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="col-md-8 offset-md-2">
            <h1>{{isset($customer)?'Edit':'New'}} Customer</h1>
            <hr/>
            @if(isset($customer))
                {!! Form::model($customer,['method'=>'put']) !!}
            @else
                {!! Form::open() !!}
            @endif
            <div class="form-group row required">
                {!! Form::label("name","Name",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
                <div class="col-md-8">
                    {!! Form::text("name",null,["class"=>"form-control".($errors->has('name')?" is-invalid":""),"autofocus",'placeholder'=>'Name']) !!}
                    {!! $errors->first('name','<span class="invalid-feedback">:message</span>') !!}
                </div>
            </div>
            <div class="form-group row">
                {!! Form::label("gender","Gender",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
                <div class="col-md-8">
                    {!! Form::select("gender",['Male'=>'Male','Female'=>'Female'],null,["class"=>"form-control"]) !!}
                </div>
            </div>
            <div class="form-group row required">
                {!! Form::label("email","Email",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
                <div class="col-md-8">
                    {!! Form::text("email",null,["class"=>"form-control".($errors->has('email')?" is-invalid":""),'placeholder'=>'Email']) !!}
                    {!! $errors->first('email','<span class="invalid-feedback">:message</span>') !!}
                </div>
            </div>
            <div class="form-group row">
                <div class="col-md-3 col-lg-2"></div>
                <div class="col-md-4">
                    <a href="{{url('laravel-crud-search-sort')}}" class="btn btn-danger">
                        Back</a>
                    {!! Form::button("Save",["type" => "submit","class"=>"btn
                btn-primary"])!!}
                </div>
            </div>
            {!! Form::close() !!}
        </div>
    </div>
@endsection

 

Step 6: Create Controller

Create controller file Crud2Controller in /demo/app/Http/Cotrollers.

<?php
namespace App\Http\Controllers;

use App\Customer;
use Illuminate\Http\Request;

class Crud2Controller extends Controller
{
    public function index(Request $request)
    {
        $search = $request->get('search');
        $gender = $request->get('gender') != '' ? $request->get('gender') : -1;
        $field = $request->get('field') != '' ? $request->get('field') : 'name';
        $sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
        $customers = new Customer();
        if ($gender != -1)
            $customers = $customers->where('gender', $gender);
        $customers = $customers->where('name', 'like', '%' . $search . '%')
            ->orderBy($field, $sort)
            ->paginate(5)
            ->withPath('?search=' . $search . '&gender=' . $gender . '&field=' . $field . '&sort=' . $sort);
        return view('crud_2.index', compact('customers'));
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
            return view('crud_2.form');
        else {
            $rules = [
                'name' => 'required',
                'email' => 'required|email',
            ];
            $this->validate($request, $rules);
            $customer = new Customer();
            $customer->name = $request->name;
            $customer->gender = $request->gender;
            $customer->email = $request->email;
            $customer->save();
            return redirect('/laravel-crud-search-sort');
        }
    }

    public function delete($id)
    {
        Customer::destroy($id);
        return redirect('/laravel-crud-search-sort');
    }

    public function update(Request $request, $id)
    {
        if ($request->isMethod('get'))
            return view('crud_2.form', ['customer' => Customer::find($id)]);
        else {
            $rules = [
                'name' => 'required',
                'email' => 'required|email',
            ];
            $this->validate($request, $rules);
            $customer = Customer::find($id);
            $customer->name = $request->name;
            $customer->gender = $request->gender;
            $customer->email = $request->email;
            $customer->save();
            return redirect('/laravel-crud-search-sort');
        }
    }
}

 

Step 7: Test

Open your browser and type http://localhost/demo/public/laravel-crud-search-sort. Then you will see it.

laravel 5.5 CRUD search sort pagination

Hope you can do it.


Demo


Related Posts

© 2018 All Rights Reserved.