Laravel 5.5 – simple crud operation with example

Laravel 5.5 – simple crud operation with example

In this post we will give you information about Laravel 5.5 – simple crud operation with example. Hear we will give you detail about Laravel 5.5 – simple crud operation with exampleAnd how to use it also give you demo for it if it is necessary.

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 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 >
        <div >
          <div >
            <!-- Collapsed Hamburger -->
            <button type="button"  data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
            <span >Toggle Navigation</span>
            <span ></span>
            <span ></span>
            <span ></span>
            </button>
            <!-- Branding Image -->
            <a  href="{{ url('/home') }}">
            CBTF
            </a>
          </div>
          <div  id="app-navbar-collapse">
            <!-- Left Side Of Navbar -->
            <ul >
               
            </ul>
            <!-- Right Side Of Navbar -->
            <ul >
              <!-- 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 >
                <a href="#"  data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
                {{ Auth::user()->name }} <span ></span>
                </a>
                <ul >
                  <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 >
        <div >
          <div >
            @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" >
  <div id="custom-width-modal"  tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;">
    <div  style="width:55%;">
      <div >
        <div >
          <button type="button"  data-dismiss="modal" aria-hidden="true">×</button>
          <h4  id="custom-width-modalLabel">Delete Record</h4>
        </div>
        <div >
          <h4>You Want You Sure Delete This Record?</h4>
        </div>
        <div >
          <button type="button"  data-dismiss="modal">Close</button>
          <button type="submit" >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  role="alert">
  <button type="button"  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  role="alert">
  <button type="button"  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  role="alert">
  <button type="button"  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  role="alert">
  <button type="button"  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  role="alert">
  <button type="button"  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 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 IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

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 in this file.




namespace App;

use IlluminateDatabaseEloquentModel;

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 in this file.




namespace AppHttpControllers;

use AppHttpRequests;
use IlluminateHttpRequest;
use AppTip;

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 in this file for all tips listing.




@extends('layouts.app')
@section('content')
<div >
  <div >
    <div >
      <div >
        <div >
          <div >
            <div >
              <strong>All Tips Listing</strong>
            </div>
            <div >
              <a href="{{ URL::route('tips.create') }}" >Add Tips</a>
            </div>
          </div>
        </div>
        <div >
          <table >
            <tr>
              <th>Title</th>
              <th width="500">Tips Description</th>
              <th width="180" >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_de($value->tips)), 0, 100) . '.....' !!}
                @else
                {!! strip_tags($value->tips) !!}
                @endif
              </td>
              <td >
                <a href="{!! URL::route('tips.edit', $value->id) !!}" >Edit</a>
                <a data-toggle="modal" data-url="{!! URL::route('tips.destroy', $value->id) !!}" data-id="{{$value->id}}" data-target="#custom-width-modal" >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 and path in your this file.




@extends('layouts.app')
@section('content')
<div >
  <div >
    <div >
      <div >
        <div >Create Tip</div>
        <div >
          <form  method="POST" action="{{ route('tips.store') }}">
            {{ csrf_field() }}
            <div >
              <label for="title" >Title</label>
              <div >
                <input id="title" type="text"  name="title" value="{{ old('title') }}" required autofocus>
                @if ($errors->has('title'))
                <span >
                <strong>{{ $errors->first('title') }}</strong>
                </span>
                @endif
              </div>
            </div>
            <div >
              <label for="tips" >Tips Description</label>
              <div >
                <pre id="tips" rows="6"  name="tips" required>{{ old('tips') }}</pre>
                @if ($errors->has('tips'))
                <span >
                <strong>{{ $errors->first('tips') }}</strong>
                </span>
                @endif
              </div>
            </div>
            <div >
              <div >
                <button type="submit" >
                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 like that




@extends('layouts.app')
@section('content')
<div >
  <div >
    <div >
      <div >
        <div >Edit Tip</div>
        <div >
          {{ Form::model($data, ['route' => ['tips.update', $data->id], 'method' => 'patch', 'class' =>'form-horizontal']) }} 
          <div >
            <label for="title" >Title</label>
            <div >
              <input id="title" type="text"  name="title" value="{{ $data->title }}" required autofocus>
              @if ($errors->has('title'))
              <span >
              <strong>{{ $errors->first('title') }}</strong>
              </span>
              @endif
            </div>
          </div>
          <div >
            <label for="tips" >Tips Description</label>
            <div >
              <pre id="tips" rows="6"  name="tips" required>{{ $data->tips }}</pre>
              @if ($errors->has('tips'))
              <span >
              <strong>{{ $errors->first('tips') }}</strong>
              </span>
              @endif
            </div>
          </div>
          <div >
            <div >
              <button type="submit" >
              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 Laravel’s Forums

Hope this and post will helped you for implement Laravel 5.5 – simple crud operation with example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

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

8  +  2  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US