Laravel 5.5 - simple crud operation with example

Today, we are sharing how to make simple laravel CRUD(insert, update, delete or listing) operations with example. Every new laravel developer need to start learning laravel with some simple CRUD because they are very fundamentals of any laravel application. We will guide you how to make simple crud in laravel step by step. We are starting with how to create laravel new project in your system how to set database setting etc... in this tutorials.

There are many laravel crud generator package is available on github but this is no meaning if you are not know how is work. You can only get to know this logic if you know how to work on laravel crud manualy. So, in this post you will learn step by step all crud operation like record listing, record inserting, record updating or editing and record deleted with confirm alert box. Simply follow each and every step and make laravel crud easily.

In this tutorial we are making CRUD for tips table. After all these steps, your output will look like this.

Create Laravel Project:

First, we need to create fresh laravel application by runing following command in your terminal.


composer create-project --prefer-dist laravel/laravel your_project_name
	
Configure .env file:

After creating a laravel project, open your project in your any editor and open .env file and configure your database setting in .env change following value in that file like that


DB_DATABASE=databasename
DB_USERNAME=phpmyadminusername
DB_PASSWORD=phpmyadminpassword	
	
Make Laravel Auth:

Next, we are create laravel bydefault authentication by run following command. laravel provide ready made authentication system so we are use that.


php artisan make:auth	
	
Create Route:

Now, open your routes/web.php file and add one route recource in this file for our tips crud. here i am use resource instade of all saperate route.


Route::resource('tips', 'TipsController');
	

Simple add above line in your web.php file

Change in app.blade.php file:

Next, we are change some in resources/views/layouts/app.blade.php file so, open this file and simply copy this all code and past in your app.blade.php file.


<!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() }}">
    <title>{{ config('app.name', 'Laravel') }}</title>
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <script type="text/javascript">
      var current_page_url = "<?php echo URL::current(); ?>";
      var current_page_fullurl = "<?php echo URL::full(); ?>";
      var CSRF_TOKEN='{{ csrf_token() }}';
    </script>
  </head>
  <body>
    <div id="app">
      <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
          <div class="navbar-header">
            <!-- Collapsed Hamburger -->
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
            <span class="sr-only">Toggle Navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <!-- Branding Image -->
            <a class="navbar-brand" href="{{ url('/home') }}">
            CBTF
            </a>
          </div>
          <div class="collapse navbar-collapse" id="app-navbar-collapse">
            <!-- Left Side Of Navbar -->
            <ul class="nav navbar-nav">
               
            </ul>
            <!-- Right Side Of Navbar -->
            <ul class="nav navbar-nav navbar-right">
              <!-- Authentication Links -->
              @guest
              <li><a href="{{ route('login') }}">Login</a></li>
              <li><a href="{{ route('register') }}">Register</a></li>
              @else
              <li><a href="{{ URL::route('tips.index') }}">Tips</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
                {{ Auth::user()->name }} <span class="caret"></span>
                </a>
                <ul class="dropdown-menu">
                  <li>
                    <a href="{{ route('logout') }}"
                      onclick="event.preventDefault();
                      document.getElementById('logout-form').submit();">
                    Logout
                    </a>
                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                      {{ csrf_field() }}
                    </form>
                  </li>
                </ul>
              </li>
              @endguest
            </ul>
          </div>
        </div>
      </nav>
      <div class="container">
        <div class="row">
          <div class="col-md-10 col-md-offset-1">
            @include('alert')
          </div>
        </div>
      </div>
      @yield('content')
    </div>
    @include('deleteModel')
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    <script src="{{ asset('js/custom.js') }}"></script>
  </body>
</html>
	
Create deleteModel.blade.php file:

Now, create deleteModel.blade.php file for delete confurm model on this path resources/views


<form action="" method="POST" class="remove-record-model">
  <div id="custom-width-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog" style="width:55%;">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title" id="custom-width-modalLabel">Delete Record</h4>
        </div>
        <div class="modal-body">
          <h4>You Want You Sure Delete This Record?</h4>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default waves-effect remove-data-from-delete-form" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-danger waves-effect waves-light">Delete</button>
        </div>
      </div>
    </div>
  </div>
</form>
	
Create alert.blade.php file:

Now, create alert.blade.php file in this path resources/views we are create this file for all alert like when we are insert data and display success message and failed message or any warning message.


@if ($errors->any())
<div class="alert alert-danger alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Error Alert!</strong> Please check the form below for errors
</div>
@endif
@if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Success Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('success');?>
@endif
@if ($message = Session::get('error'))
<div class="alert alert-danger alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Error Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('error');?>
@endif
@if ($message = Session::get('warning'))
<div class="alert alert-warning alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Waarning Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('warning');?>
@endif
@if ($message = Session::get('info'))
<div class="alert alert-indo alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Information Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('info');?>
@endif
	
Create custom.js File:

Now, we are create custom.js file on this path public/js and in this file we are write js code for out delete confirm model. this js logic you can use any your laravel application for delete records with confirmation model.


$(document).ready(function(){
	// For A Delete Record Popup
	$('.remove-record').click(function() {
		var id = $(this).attr('data-id');
		var url = $(this).attr('data-url');
		var token = CSRF_TOKEN;
		$(".remove-record-model").attr("action",url);
		$('body').find('.remove-record-model').append('<input name="_token" type="hidden" value="'+ token +'">');
		$('body').find('.remove-record-model').append('<input name="_method" type="hidden" value="DELETE">');
		$('body').find('.remove-record-model').append('<input name="id" type="hidden" value="'+ id +'">');
	});

	$('.remove-data-from-delete-form').click(function() {
		$('body').find('.remove-record-model').find( "input" ).remove();
	});
	$('.modal').click(function() {
		// $('body').find('.remove-record-model').find( "input" ).remove();
	});
});	
	
Create tips Table Migration:

Now, we are create tips table migration by run following command in terminal.


php artisan make:migration create_tips_tbl
	

After runing this command in your terminal then one mingration file automatic generated in your this path database/migrations/ then here your show one new migration file so, open it and change like thai in this file.


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

class CreateTipsTbl extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tips', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->nullble();
            $table->text('tips')->nullble();
            $table->timestamps();
        });
    }

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

After change in this migration file then run this migration by following command in your terminal.


php artisan migrate

After run this command then your tips table automatic generated in database.

Create tips Table Model:

Now, create tips table model in following path app/Tip.php and add following code in this file.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Tip extends Model
{
    protected $table = 'tips';
    protected $guarded = array();

    public function getData()
    {
        return static::orderBy('id', 'desc')->paginate(5);
    }

    public function AddData($input)
    {
        return static::create($input);
    }

    public function findData($id)
    {
        return static::find($id);
    }

    public function updateData($id, $input)
    {
        return static::where('id', $id)->update($input);
    }

    public function destroyData($id)
    {
        return static::where('id',$id)->delete();
    }
}

Create TipsController:

Now, create TipsController.php file in this path app/Http/Controllers and simple copy this following code in this file.


namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\Tip;

class TipsController extends HomeController
{
    public function __construct()
    {
        parent::__construct();

        $this->Tip = new Tip;

        $this->moduleTitleS = 'Tips';
        $this->moduleTitleP = 'Tips';

        view()->share('moduleTitleP',$this->moduleTitleP);
        view()->share('moduleTitleS',$this->moduleTitleS);
    }
    
    public function index()
    {
        $data = $this->Tip->getData();
        
        return view($this->moduleTitleP.'.index',compact('data'))
                         ->with('i',0);
    }
    
    public function create()
    {
        return view($this->moduleTitleP.'.create');
    }
   
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
            'tips' => 'required',
        ]);

        $input = array_except($request->all(),array('_token'));

        $this->Tip->AddData($input);

        \Session::put('success','Tip Store Successfully!!');

        return redirect()->route('tips.index');
    }

    public function edit($id)
    {
        $data = $this->Tip->findData($id);

        return view($this->moduleTitleP.'.edit',compact('data'));
    }
    
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
            'tips' => 'required',
        ]);

        $input = array_except($request->all(),array('_token', '_method'));

        $this->Tip->updateData($id, $input);

        \Session::put('success','Tip Updated Successfully!!');

        return redirect()->route('tips.index');
    }
    
    public function destroy($id)
    {
        $this->Tip->destroyData($id);

        \Session::put('success','Post Delete Successfully!!');

        return redirect()->route('tips.index');
    }
}	
	
Create All View Blade File:

Now, we are create all following blade file one by one

1.)index.blade.php

2.)create.blade.php

3.)edit.blade.php

resources/views/Tips/index.blade.php File:

Now, create this file and simply copy and path following code in this file for all tips listing.


@extends('layouts.app')
@section('content')
<div class="container">
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      <div class="panel panel-default">
        <div class="panel-heading">
          <div class="row">
            <div class="col-md-10">
              <strong>All Tips Listing</strong>
            </div>
            <div class="col-md-2">
              <a href="{{ URL::route('tips.create') }}" class="btn btn-info pull-right">Add Tips</a>
            </div>
          </div>
        </div>
        <div class="panel-body">
          <table class="table table-bordered">
            <tr>
              <th>Title</th>
              <th width="500">Tips Description</th>
              <th width="180" class="text-center">Action</th>
            </tr>
            @if(!empty($data) && $data->count())
            @foreach($data as $key => $value)
            <tr>
              <td>{{ $value->title }}</td>
              <td>
                @if (strlen($value->tips) > 100)
                {!! substr(strip_tags(html_entity_decode($value->tips)), 0, 100) . '.....' !!}
                @else
                {!! strip_tags($value->tips) !!}
                @endif
              </td>
              <td class="text-center">
                <a href="{!! URL::route('tips.edit', $value->id) !!}" class="btn btn-success">Edit</a>
                <a data-toggle="modal" data-url="{!! URL::route('tips.destroy', $value->id) !!}" data-id="{{$value->id}}" data-target="#custom-width-modal" class="btn btn-danger remove-record">Delete</a>
              </td>
            </tr>
            @endforeach
            @endif
          </table>
        </div>
      </div>
      {!! $data->appends([])->render() !!}
    </div>
  </div>
</div>
@endsection
	
resources/views/Tips/create.blade.php File:

Now, create this file for create and insert tips records in our database. simply copy this all following code and path in your this file.


@extends('layouts.app')
@section('content')
<div class="container">
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      <div class="panel panel-default">
        <div class="panel-heading">Create Tip</div>
        <div class="panel-body">
          <form class="form-horizontal" method="POST" action="{{ route('tips.store') }}">
            {{ csrf_field() }}
            <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
              <label for="title" class="col-md-3 control-label">Title</label>
              <div class="col-md-7">
                <input id="title" type="text" class="form-control" name="title" value="{{ old('title') }}" required autofocus>
                @if ($errors->has('title'))
                <span class="help-block">
                <strong>{{ $errors->first('title') }}</strong>
                </span>
                @endif
              </div>
            </div>
            <div class="form-group{{ $errors->has('tips') ? ' has-error' : '' }}">
              <label for="tips" class="col-md-3 control-label">Tips Description</label>
              <div class="col-md-7">
                <textarea id="tips" rows="6" class="form-control" name="tips" required>{{ old('tips') }}</textarea>
                @if ($errors->has('tips'))
                <span class="help-block">
                <strong>{{ $errors->first('tips') }}</strong>
                </span>
                @endif
              </div>
            </div>
            <div class="form-group">
              <div class="col-md-7 col-md-offset-3">
                <button type="submit" class="btn btn-primary btn-block">
                Submit
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection	
	

resources/views/Tips/edit.blade.php

Now, we are create edit file for update any record in our database. this code like that


@extends('layouts.app')
@section('content')
<div class="container">
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      <div class="panel panel-default">
        <div class="panel-heading">Edit Tip</div>
        <div class="panel-body">
          {{ Form::model($data, ['route' => ['tips.update', $data->id], 'method' => 'patch', 'class' =>'form-horizontal']) }} 
          <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
            <label for="title" class="col-md-3 control-label">Title</label>
            <div class="col-md-7">
              <input id="title" type="text" class="form-control" name="title" value="{{ $data->title }}" required autofocus>
              @if ($errors->has('title'))
              <span class="help-block">
              <strong>{{ $errors->first('title') }}</strong>
              </span>
              @endif
            </div>
          </div>
          <div class="form-group{{ $errors->has('tips') ? ' has-error' : '' }}">
            <label for="tips" class="col-md-3 control-label">Tips Description</label>
            <div class="col-md-7">
              <textarea id="tips" rows="6" class="form-control" name="tips" required>{{ $data->tips }}</textarea>
              @if ($errors->has('tips'))
              <span class="help-block">
              <strong>{{ $errors->first('tips') }}</strong>
              </span>
              @endif
            </div>
          </div>
          <div class="form-group">
            <div class="col-md-7 col-md-offset-3">
              <button type="submit" class="btn btn-primary btn-block">
              Update
              </button>
            </div>
          </div>
          {{ Form::close() }}
        </div>
      </div>
    </div>
  </div>
</div>
@endsection	
	

Now we are ready to run our example so run bellow command ro quick run:


php artisan serve

Now you can test one by one route url in your browser like that:


http://localhost:8000/tips

We are hope you like this tutorials, if any question regarding any query please post your question in our forums click on bellow link Laravelcode's Forums

 Prev post

Next post