CRUD Operation (Create Read Update Delete) in Laravel 5.7

We are here to see the demo of the CRUD operation in Laravel. It means we have already set up the Laravel. The first thing we need to do is create a migration of our database table. In this post, we are going to create a CRUD operation on the customers’ table.

If you did not installed Laravel app yet then check this one first before creating CRUD Operation. Install Laravel

 Create a Migration for customers table

php artisan make:migration create_customers_table --create=customers

Above code will generate a new file in the following path. {YourAppName}->database->migrations->{AutoGeneratedMigarationFile.php}.

You will also find two more migration files there which are default files provided by Laravel.

You have to update our migration file as shown in below code.
Compare your file and below code and see the difference. Here only few lines are added in Schema.

<?php

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

class CreateCustomersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email');
            $table->string('mobile');
            $table->timestamps();
        });
    }

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

Run the Migrate (Create a table from Schema)

Now its time to create a table based on Schema we have created in the above file. Run the following command to create a table in database using the schema from migration file.

php artisan migrate

Create a Model

php artisan make:model Customer
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    //
    protected $table = 'customers';
}

Create a Resource Controller

php artisan make:controller CustomerController --resource
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Create a Route

Route::resource('customer', 'CustomerController');

Create a Resource File

First Create the Main Layout File. In this example, the path is like this.

resources > views > layouts > main.blade.php
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous">

    <title>Hectacode</title>
  </head>
  <body>
    @yield('content')
  </body>
</html>

Generate three more blade files for Customer List, Create and Edit.

resources > views > customer > index.blade.php
@extends('layouts.main')

@section('content')
<main role="main" class="container">

    <div class="row mt-5">
        <div class="col-md-6">
          <h1>Customer Listing</h1>
        </div>
        <div class="col-md-6">
          <a class="btn btn-primary pull-right" href="{{ route('customer.create') }}">Add New Customer</a>
        </div>
    </div>
    <div>
      <div class="col-md-12">
        @if (Session::has('message'))
        <div class="alert alert-info">
        <p>{{ Session::get('message') }}</p>
        </div>
        @endif
      </div>
    </div>
    <div class="row">
      <div class="table-responsive">
        <table class="table">
        @if(count($Customers) > 0)
               <thead>
                  <tr>
                    <th scope="col">#</th>
                    <th scope="col">First Name</th>
                    <th scope="col">Last Name</th>
                    <th scope="col">Email </th>
                    <th scope="col">Mobile</th>
                    <th scope="col"> Action</th>
                  </tr>
                </thead>
                <tbody>
                  @foreach($Customers as $Customer)
                    <tr>
                      <th scope="row"></th>
                      <td>{{ $Customer->first_name }}</td>
                      <td>{{ $Customer->last_name }}</td>
                      <td>{{ $Customer->email }}</td>
                      <td>{{ $Customer->mobile }}</td>
                      <td><a class="btn btn-info" href="{{ route('customer.edit', $Customer->id) }}">Edit</a><form method="post" action="{{ route('customer.destroy', $Customer->id) }}">
                      <input name="_method" type="hidden" value="DELETE">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                      <button type="submit" class="btn btn-danger">Delete</button>
                      </form>
                      </td>
                    </tr>
                  @endforeach
                </tbody>
        @else
          There is No customers added yet
        @endif
          </table>
        </div>
    </div>
</min>
@endsection
resources > views > customer > create.blade.php
@extends('layouts.main')

@section('content')
<div class="container">
    <div class="row">
        <form action="{{ route('customer.store') }}" method="POST">
            @csrf
            <div class="form-group">
              <label for="first_name">First Name:</label>
              <input type="text" class="form-control" id="first_name" placeholder="Enter First Name" name="first_name">
            </div>

            <div class="form-group">
              <label for="last_name">Last Name:</label>
              <input type="text" class="form-control" id="last_name" placeholder="Enter Last Name" name="last_name">
            </div>

            <div class="form-group">
              <label for="email">Email:</label>
              <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
            </div>
            <div class="form-group">
                <label for="mobile">Mobile:</label>
                <input type="text" class="form-control" id="mobile" placeholder="First Mobile" name="mobile">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
</div>
@endsection
resources > views > customer > edit.blade.php
@extends('layouts.main')

@section('content')
<div class="container">
    <div class="row">
        <form action="{{ route('customer.update', $Customer->id) }}" method="POST">
            @csrf
            {{ method_field('PUT') }}
            <div class="form-group">
              <label for="first_name">First Name:</label>
              <input type="text" class="form-control" id="first_name" placeholder="Enter First Name" name="first_name" value="{{ $Customer->first_name }}">
            </div>

            <div class="form-group">
              <label for="last_name">Last Name:</label>
              <input type="text" class="form-control" id="last_name" placeholder="Enter Last Name" name="last_name" value="{{ $Customer->last_name }}">
            </div>

            <div class="form-group">
              <label for="email">Email:</label>
              <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" value="{{ $Customer->email }}">
            </div>
            <div class="form-group">
                <label for="mobile">Mobile:</label>
                <input type="text" class="form-control" id="mobile" placeholder="Enter Mobile" name="mobile" value="{{ $Customer->mobile }}">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
</div>
@endsection

Update the latest code in CustomerController.php as below. Then run the server.

<?php

namespace App\Http\Controllers;

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

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $Customers = Customer::get();
        return view('customer.index')->with(['Customers'=>$Customers]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('customer.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $inputs = $request->all();

        Customer::create($inputs);

        return redirect()->route('customer.index')->withMessage('Customer was added Successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $Customer = Customer::find($id);
        return view('customer.edit')->with(['Customer'=>$Customer]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //

        $Customer = Customer::find($id);
        $Customer->first_name = $request->first_name;
        $Customer->last_name = $request->last_name;
        $Customer->email = $request->email;
        $Customer->mobile = $request->mobile;
        $Customer->save();

        return redirect()->route('customer.index')->withMessage('Customer was updated Successfully');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Customer::destroy($id);

        return redirect()->route('customer.index')->withMessage('Customer was deleted Successfully');
    }
}

Leave a Reply

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