How to create easy CRUD with Laravel 5.5

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

As a developer, basically we should know how to manage data with database. So this tutorial I want to show you how to create an easy CRUD (Create, Read, Update, Delete) 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-easy-crud'], function () {
    Route::get('/', 'Crud1Controller@index');
    Route::match(['get', 'post'], 'create', 'Crud1Controller@create');
    Route::match(['get', 'put'], 'update/{id}', 'Crud1Controller@update');
    Route::delete('delete/{id}', 'Crud1Controller@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_1. (create folder crud_1 if it does not exist)

@extends('layout.default')
@section('content')
    <div class="container">
        <div class="float-right">
            <a href="{{url('laravel-easy-crud/create')}}" class="btn btn-primary">New</a>
        </div>
        <h1 style="font-size: 2.2rem">Customers List (Laravel 5.5 CRUD Example)</h1>
        <hr/>
        <table class="table table-bordered bg-light">
            <thead class="bg-dark" style="color: white">
            <tr>
                <th width="60px" style="text-align: center">No</th>
                <th>Name</th>
                <th>Gender</th>
                <th>Email</th>
                <th width="150px">Action</th>
            </tr>
            </thead>
            <tbody>
            @php
                $i=1;
            @endphp
            @foreach($customers as $customer)
                <tr>
                    <th style="text-align: center">{{$i++}}</th>
                    <td>{{$customer->name}}</td>
                    <td>{{$customer->gender}}</td>
                    <td>{{$customer->email}}</td>
                    <td align="center">
                        <form id="frm_{{$customer->id}}"
                              action="{{url('laravel-easy-crud/delete/'.$customer->id)}}"
                              method="post" style="padding-bottom: 0px;margin-bottom: 0px">
                            <a class="btn btn-primary btn-sm" title="Edit"
                               href="{{url('laravel-easy-crud/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_1. (create folder crud_1 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-easy-crud')}}" 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 Crud1Controller in /demo/app/Http/Cotrollers.

<?php
namespace App\Http\Controllers;

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

class Crud1Controller extends Controller
{
    public function index()
    {
        $customers = Customer::orderBy('created_at', 'desc')->paginate(5);
        return view('crud_1.index', compact('customers'));
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
            return view('crud_1.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-easy-crud');
        }
    }

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

    public function update(Request $request, $id)
    {
        if ($request->isMethod('get'))
            return view('crud_1.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-easy-crud');
        }
    }
}

 

Step 7: Test

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

laravel 5.5 easy CRUD

Hope you can do it.


Demo


Related Posts

© 2018 All Rights Reserved.