Laravel 5.6 CRUD Tutorial Using Resource Controller

This laravel 5.6 tutorial help to create CRUD functionality using Resource Controller .CRUD AKA Creating, Reading, Updating, and Deleting resources from database.You can create these operation using Laravel Resource very easily. The Laravel makes easy to create CRUD operation using Resources Controller.

Laravel very fast and popular PHP MVC framework. Laravel resource routing assigns the typical “CRUD” routes to a controller with a single line of code.

In this laravel tutorial, we will let you know the process of CRUD opeation for employee module.The employee module will have create, read, update, and delete (CRUD) a resource.

CRUD Operation Using Resource Controller in Laravel 5.6

I am assuming, you have created laravel application and connected database using .env file.We will create new controller, model and view to access CRUD features.

Laravel Migration File

We will create laravel migration file using below command.

php artisan make:migration create_employee_table

Above command will create migration file into database/migrations/2018_09_17_060245_create_employee_table.php .

Now open database/migrations/2018_09_17_060245_create_employee_table.php file and add below table column information into this file.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
 
class CreateEmployeeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employee', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255);
            $table->integer('salary');
            $table->integer('age');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employee');
    }
}

We will migrate table into database using below command.

php artisan migrate

Above command will create employee table into your connected database.Please make sure your database settings are good in app/config/database.php file:

We will create Employee model using below command.You can get model file into controllers/ folder

php artisan make:model Employee

Laravel has en-build command to do specific operation like create controller, create migration file and migrate table, create model, create event and listeners etc, that is grouped under Artisan command, I will use Artisan command to create resource controller using below command, This Controller will have have all CRUD operation method declaration that handles all operation for employee module.

php artisan make:controller EmployeeController --resource

The above command will create EmployeeController.php file into app/Http/Controllers/ folder.The controller file will contain a method for each of the available resource operations.

php artisan make:controller EmployeeController --resource --model=Employee

namespace App\Http\Controllers;
 
use App\Employee;
use Illuminate\Http\Request;
 
class EmployeeController 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  \App\Employee  $employee
     * @return \Illuminate\Http\Response
     */
    public function show(Employee $employee)
    {
        //
    }
 
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Employee  $employee
     * @return \Illuminate\Http\Response
     */
    public function edit(Employee $employee)
    {
        //
    }
 
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Employee  $employee
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Employee $employee)
    {
        //
    }
 
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Employee  $employee
     * @return \Illuminate\Http\Response
     */
    public function destroy(Employee $employee)
    {
        //
    }
}

Now we will make route entry into routes/web.php file.

Route::resource('employee', 'EmployeeController');

The above resource routes will handle following operations:

HTTP Method Path (URL) Action (Method) Route Name
GET /employee index employee.index
GET /employee/create create employee.create
POST /employee store employee.store
GET /employee/{id} show employee.show
GET /employee/{id}/edit edit employee.edit
PUT/PATCH /employee/{id} update employee.update
DELETE /employee/{id} destroy employee.destroy

How To Create HTML Views in Laravel 5.6

The resources folder have all views of the application modules, You can create manually or using artisan CLI.

The following artisan CLI command will create employee module view files for templating into laravel:

php artisan make:view employee --resource

The above command has been created employee/ folder into resources/views/ folder.This folder contains index.blade.html , create.blade.html and edit.blade.html file.

How To Create Listing in Laravel 5.6

The index blade template is use to display list all records.The controller method index() is responsible to get all record from employee table.We will add below code into resources/views/employee/index.blade.html file:

<h1>All the Employees</h1>
 
<!-- will be used to show any messages -->
@if (Session::has('message'))
    <div class="alert alert-info">{{ Session::get('message') }}</div>
@endif
 
<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Salaray</td>
            <td>Age</td>
            <td>Actions</td>
        </tr>
    </thead>
    <tbody>
    @foreach($employees as $key => $emp)
        <tr>
            <td>{{ $emp->id }}</td>
            <td>{{ $emp->name }}</td>
            <td>{{ $emp->salary }}</td>
            <td>{{ $emp->age }}</td>
 
            <!-- we will also add show, edit, and delete buttons -->
            <td>
 
                <!-- delete the nerd (uses the destroy method DESTROY /nerds/{id} -->
                <!-- we will add this later since its a little more complicated than the other two buttons -->
 
                <!-- show the nerd (uses the show method found at GET /nerds/{id} -->
                <a class="btn btn-small btn-success" href="{{ URL::to('employee/' . $emp->id) }}">Show</a>
 
                <!-- edit this nerd (uses the edit method found at GET /nerds/{id}/edit -->
                <a class="btn btn-small btn-info" href="{{ URL::to('employee/' . $emp->id . '/edit')}}">Edit</a>
 
            </td>
        </tr>
    @endforeach
    </tbody>
</table>

How to Add Record Into Laravel 5.6

We have created add new employee record action into EmployeeController file, Now we will create HTML file and added action method into form.

<h1>The Employees</h1>
 
<!-- will be used to show any messages -->
@if (Session::has('message'))
    <div class="alert alert-info">{{ Session::get('message') }}</div>
@endif
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
<form method="post" action="{{ route('employee.store')}}" accept-charset="UTF-8">
  <div class="col-md-12">
   <div class="form-area">
   <div class="alert alert-success hide"></div>
    <input name="_token" type="hidden" value="{{ csrf_token() }}"/>
   <div class="alert alert-danger hide"></div>
   <div class="form-group">
 <input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" placeholder="Name"/>
 @if ($errors->has('name'))
 <span class="alert-danger">dsssssssssssssssssss</span>
 @endif
   </div>
   <div class="form-group">
 <input type="number" pattern="[0-9]*"  class="form-control" id="salary" name="salary" placeholder="Salary Number" />
   </div>
   <div class="form-group">
 <input class="form-control" type="number" id="age" name="age" placeholder="age"></textarea>               
   </div>
   <button type="submit" id="submit" name="submit" class="btn btn-primary pull-right">Submit Employee</button>
   </div>
 </div>
 </form>

There are two controller method will participate into add new record functionality in laravel, The create() method is use to show create view and store() method is used to stored the form data into database.I am using MySQL, SO that record will saved into MySQL employee table.

You can add all data related operations and validation into store() method.

How to Update Record Into Laravel 5.6

We have created update employee record action into EmployeeController file, Now we will create edit HTML file using blade template engine.

@if (Session::has('message'))
    <div class="alert alert-info">{{ Session::get('message') }}</div>
@endif
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
 
      <div class="col-md-12">
          <div class="form-area">  
            <form role="form" method="post" action="{{ route('employee.update', $employee->id)}}" accept-charset="UTF-8">
              <div class="alert alert-success hide"></div>
               <input name="_token" type="hidden" value="{{ csrf_token() }}"/>
              <div class="alert alert-danger hide"></div>
              <div class="form-group">
                <input type="text" class="form-control" id="name" name="name" value="{{$employee->name}}" placeholder="Name"/>
              </div>
              <div class="form-group">
                <input type="number" pattern="[0-9]*"  class="form-control" id="salary" name="salary" value="{{ $employee->salary }}" placeholder="Salary Number" />
              </div>
              <div class="form-group">
                <input class="form-control" type="number" id="age" name="age" placeholder="age" value="{{ $employee->age }}"/>               
              </div>
              <button type="submit" id="submit" name="submit" class="btn btn-primary pull-right">Submit Employee</button>
            </form>
          </div>
        </div>
     </form>

The form action is set 'employee.update' , The update() method is defined into EmployeeController to update data.The edit() action is defined to display edit template.