Laravel 5.2 CRUD (Create Read Update Delete) Example from Scratch

Laravel 5.2 CRUD (Create Read Update Delete) Example from Scratch

In this post we will give you information about Laravel 5.2 CRUD (Create Read Update Delete) Example from Scratch. Hear we will give you detail about Laravel 5.2 CRUD (Create Read Update Delete) Example from ScratchAnd how to use it also give you demo for it if it is necessary.

Laravel 5.2 CRUD (Create Read Update Delete) Example from Scratch

I am going to explain how to create a single module with Laravel CRUD (Create, Read, Update, Delete) application.Kindly follow each step to create a simple CRUD application.I assure you, if you follow these steps properly then you won’t get any error.In this CRUD application, you can add new product, edit those products, view product details and delete product.

Before going to start, kindly let you know following things :

  • Know about PHP OOP Concept, Click here to know Basic concept of Object Oriented Programming
  • What is resource route ?
  • How to validating request data ?

Step 1: Install Laravel 5.2

If Laravel is not installed in your system then first install with following command and get fresh Laravel project.

composer create-project --prefer-dist laravel/laravel blog "5.2.*"

When you run above command then it create application with name blog in your system.From Laravel 5, you have to install laravelcollective/html for Form class.To know the installation process of laravelcollective/html, kindly go through this url HTML/FORM not found in Laravel 5?.

Step 2: Create products table and model

Follow the simple step to create products table in your database.First create migration for products table using Laravel 5 php artisan command,so first run this command –

php artisan make:migration create_products_table

After this command, you will see a migration file in following path database/migrations and you have to simply put following code in migration file to create products table.

  1. use IlluminateDatabaseSchemaBlueprint;
  2. use IlluminateDatabaseMigrationsMigration;
  3. class CreateProductsTable extends Migration
  4. {
  5. public functionup()
  6. {
  7. Schema::create('products',function(Blueprint $table){
  8. $table->increments('id');
  9. $table->string('name');
  10. $table->text('details');
  11. $table->timestamps();
  12. });
  13. }
  14. public functiondown()
  15. {
  16. Schema::drop("products");
  17. }
  18. }
use IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;class CreateProductsTable extends Migration{    public function up()    {        Schema::create('products', function (Blueprint $table) {            $table->increments('id');            $table->string('name');            $table->text('details');            $table->timestamps();        });    }    public function down()    {        Schema::drop("products");    }}

Save this migration file and run following command

php artisan migrate

After create ‘products’ table, yor should create model for product table.Create file in following path app/Product.php and put bellow couple of code in Product.php file:

app/Product.php

  1. namespace App;
  2. use IlluminateDatabaseEloquentModel;
  3. class Product extends Model
  4. {
  5. public $fillable=['name','details'];
  6. }
namespace App;use IlluminateDatabaseEloquentModel;class Product extends Model{    public $fillable = ['name','details'];}

Step 3: Add Route and Controller

To handling request, you need to create route for products CRUD, so just add resource route in your routes file.I added resource route because it will add index, show, create, show and delete routes automatically.So put bellow line of code in your route file.

app/Http/routes.php

  1. Route::resource('productCRUD','ProductCRUDController');
Route::resource('productCRUD','ProductCRUDController');

Now we will create ProductCRUDController in following path app/Http/Controllers, all routes will manage by this ProductCRUDController.php file.

app/Http/Controllers/ProductCRUDController.php

  1. namespace AppHttpControllers;
  2. use IlluminateHttpRequest;
  3. use AppHttpControllersController;
  4. use AppProduct;
  5. class ProductCRUDController extends Controller
  6. {
  7. /**
  8. * Display a listing of the resource.
  9. *
  10. * @return IlluminateHttpResponse
  11. */
  12. public functionindex(Request $request)
  13. {
  14. $products= Product::orderBy('id','DESC')->paginate(5);
  15. returnview('ProductCRUD.index',compact('products'))
  16. ->with('i',($request->input('page',1)-1)*5);
  17. }
  18. /**
  19. * Show the form for creating a new resource.
  20. *
  21. * @return IlluminateHttpResponse
  22. */
  23. public functioncreate()
  24. {
  25. returnview('ProductCRUD.create');
  26. }
  27. /**
  28. * Store a newly created resource in storage.
  29. *
  30. * @param IlluminateHttpRequest $request
  31. * @return IlluminateHttpResponse
  32. */
  33. public functionstore(Request $request)
  34. {
  35. $this->validate($request,[
  36. 'name'=>'required',
  37. 'details'=>'required',
  38. ]);
  39. Product::create($request->all());
  40. returnredirect()->route('productCRUD.index')
  41. ->with('success','Product created successfully');
  42. }
  43. /**
  44. * Display the specified resource.
  45. *
  46. * @param int $id
  47. * @return IlluminateHttpResponse
  48. */
  49. public functionshow($id)
  50. {
  51. $product= Product::find($id);
  52. returnview('ProductCRUD.show',compact('product'));
  53. }
  54. /**
  55. * Show the form for editing the specified resource.
  56. *
  57. * @param int $id
  58. * @return IlluminateHttpResponse
  59. */
  60. public functionedit($id)
  61. {
  62. $product= Product::find($id);
  63. returnview('ProductCRUD.edit',compact('product'));
  64. }
  65. /**
  66. * Update the specified resource in storage.
  67. *
  68. * @param IlluminateHttpRequest $request
  69. * @param int $id
  70. * @return IlluminateHttpResponse
  71. */
  72. public functionupdate(Request $request,$id)
  73. {
  74. $this->validate($request,[
  75. 'name'=>'required',
  76. 'details'=>'required',
  77. ]);
  78. Product::find($id)->update($request->all());
  79. returnredirect()->route('productCRUD.index')
  80. ->with('success','Product updated successfully');
  81. }
  82. /**
  83. * Remove the specified resource from storage.
  84. *
  85. * @param int $id
  86. * @return IlluminateHttpResponse
  87. */
  88. public functiondestroy($id)
  89. {
  90. Product::find($id)->delete();
  91. returnredirect()->route('productCRUD.index')
  92. ->with('success','Product deleted successfully');
  93. }
  94. }
namespace AppHttpControllers;use IlluminateHttpRequest;use AppHttpControllersController;use AppProduct;class ProductCRUDController extends Controller{    /**     * Display a listing of the resource.     *     * @return IlluminateHttpResponse     */    public function index(Request $request)    {        $products= Product::orderBy('id','DESC')->paginate(5);        return view('ProductCRUD.index',compact('products'))            ->with('i', ($request->input('page', 1) - 1) * 5);    }    /**     * Show the form for creating a new resource.     *     * @return IlluminateHttpResponse     */    public function create()    {        return view('ProductCRUD.create');    }    /**     * Store a newly created resource in storage.     *     * @param  IlluminateHttpRequest  $request     * @return IlluminateHttpResponse     */    public function store(Request $request)    {        $this->validate($request, [            'name' => 'required',            'details' => 'required',        ]);        Product::create($request->all());        return redirect()->route('productCRUD.index')                        ->with('success','Product created successfully');    }    /**     * Display the specified resource.     *     * @param  int  $id     * @return IlluminateHttpResponse     */    public function show($id)    {        $product= Product::find($id);        return view('ProductCRUD.show',compact('product'));    }    /**     * Show the form for editing the specified resource.     *     * @param  int  $id     * @return IlluminateHttpResponse     */    public function edit($id)    {        $product= Product::find($id);        return view('ProductCRUD.edit',compact('product'));    }    /**     * Update the specified resource in storage.     *     * @param  IlluminateHttpRequest  $request     * @param  int  $id     * @return IlluminateHttpResponse     */    public function update(Request $request, $id)    {        $this->validate($request, [            'name' => 'required',            'details' => 'required',        ]);        Product::find($id)->update($request->all());        return redirect()->route('productCRUD.index')                        ->with('success','Product updated successfully');    }    /**     * Remove the specified resource from storage.     *     * @param  int  $id     * @return IlluminateHttpResponse     */    public function destroy($id)    {        Product::find($id)->delete();        return redirect()->route('productCRUD.index')                        ->with('success','Product deleted successfully');    }}

Step 4: Create Blade File

Now we will create blade file for listing, create, edit, show, form, default (which is master template).According to standard structure of Laravel, we create new layouts folder/directory in following path resources/views and create default.blade.php within that folderresources/views/layouts/.

resources/views/layouts/default.blade.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>Laravel CRUD</title>
  8. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
  9. </head>
  10. <body>
  11. <div class="container">
  12. @yield('content')
  13. </div>
  14. </body>
  15. </html>
<!DOCTYPE html><html lang="en"><head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>Laravel CRUD</title>    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet"></head><body> <div >    @yield('content')</div> </body></html>

Now we will create layout for product listing, for this we will create seperate directory name ProductCRUD which contain files related products functionality and create index.blade.php file within resources/views/ProductCRUD/.

resources/views/ProductCRUD/index.blade.php

  1. @extends('layouts.default')
  2. @section('content')
  3. <div class="row">
  4. <div class="col-lg-12 margin-tb">
  5. <div class="pull-left">
  6. <h2>Products CRUD</h2>
  7. </div>
  8. <div class="pull-right">
  9. <a class="btn btn-success" href="{{ route('productCRUD.create') }}"> Create New Product</a>
  10. </div>
  11. </div>
  12. </div>
  13. @if($message= Session::get('success'))
  14. <div class="alert alert-success">
  15. <p>{{$message}}</p>
  16. </div>
  17. @endif
  18. <table class="table table-bordered">
  19. <tr>
  20. <th>No</th>
  21. <th>Name</th>
  22. <th>Details</th>
  23. <th width="280px">Action</th>
  24. </tr>
  25. @foreach($productsas$product)
  26. <tr>
  27. <td>{{++$i}}</td>
  28. <td>{{$product->name}}</td>
  29. <td>{{$product->details}}</td>
  30. <td>
  31. <a class="btn btn-info" href="{{ route('productCRUD.show',$product->id) }}">Show</a>
  32. <a class="btn btn-primary" href="{{ route('productCRUD.edit',$product->id) }}">Edit</a>
  33. {!! Form::open(['method'=>'DELETE','route'=>['productCRUD.destroy',$product->id],'style'=>'display:inline'])!!}
  34. {!! Form::submit('Delete',['class'=>'btn btn-danger'])!!}
  35. {!! Form::close()!!}
  36. </td>
  37. </tr>
  38. @endforeach
  39. </table>
  40. {!!$products->render()!!}
  41. @endsection
@extends('layouts.default')@section('content')    <div >        <div >            <div >                <h2>Products CRUD</h2>            </div>            <div >                <a  href="{{ route('productCRUD.create') }}"> Create New Product</a>            </div>        </div>    </div>    @if ($message = Session::get('success'))        <div >            <p>{{ $message }}</p>        </div>    @endif    <table >        <tr>            <th>No</th>            <th>Name</th>            <th>Details</th>            <th width="280px">Action</th>        </tr>    @foreach ($products as $product)    <tr>        <td>{{ ++$i }}</td>        <td>{{ $product->name}}</td>        <td>{{ $product->details}}</td>        <td>            <a  href="{{ route('productCRUD.show',$product->id) }}">Show</a>            <a  href="{{ route('productCRUD.edit',$product->id) }}">Edit</a>            {!! Form::open(['method' => 'DELETE','route' => ['productCRUD.destroy', $product->id],'style'=>'display:inline']) !!}            {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}            {!! Form::close() !!}        </td>    </tr>    @endforeach    </table>    {!! $products->render() !!}@endsection

Now we create new blade file to add new product within ProductCRUD folder

resources/views/ProductCRUD/create.blade.php

  1. @extends('layouts.default')
  2. @section('content')
  3. <div class="row">
  4. <div class="col-lg-12 margin-tb">
  5. <div class="pull-left">
  6. <h2>Add New Product</h2>
  7. </div>
  8. <div class="pull-right">
  9. <a class="btn btn-primary" href="{{ route('productCRUD.index') }}"> Back</a>
  10. </div>
  11. </div>
  12. </div>
  13. @if(count($errors)>)
  14. <div class="alert alert-danger">
  15. <strong>Whoops!</strong> There were some problems with your input.<br><br>
  16. <ul>
  17. @foreach($errors->all()as$error)
  18. <li>{{$error}}</li>
  19. @endforeach
  20. </ul>
  21. </div>
  22. @endif
  23. {!! Form::open(array('route'=>'productCRUD.store','method'=>'POST'))!!}
  24. @include('ProductCRUD.form')
  25. {!! Form::close()!!}
  26. @endsection
@extends('layouts.default')@section('content')    <div >        <div >            <div >                <h2>Add New Product</h2>            </div>            <div >                <a  href="{{ route('productCRUD.index') }}"> Back</a>            </div>        </div>    </div>    @if (count($errors) > 0)        <div >            <strong>Whoops!</strong> There were some problems with your input.<br><br>            <ul>                @foreach ($errors->all() as $error)                    <li>{{ $error }}</li>                @endforeach            </ul>        </div>    @endif    {!! Form::open(array('route' => 'productCRUD.store','method'=>'POST')) !!}         @include('ProductCRUD.form')    {!! Form::close() !!}@endsection

Now we create new blade file to edit product within ProductCRUD folder

resources/views/ProductCRUD/edit.blade.php

  1. @extends('layouts.default')
  2. @section('content')
  3. <div class="row">
  4. <div class="col-lg-12 margin-tb">
  5. <div class="pull-left">
  6. <h2>Edit Product</h2>
  7. </div>
  8. <div class="pull-right">
  9. <a class="btn btn-primary" href="{{ route('productCRUD.index') }}"> Back</a>
  10. </div>
  11. </div>
  12. </div>
  13. @if(count($errors)>)
  14. <div class="alert alert-danger">
  15. <strong>Whoops!</strong> There were some problems with your input.<br><br>
  16. <ul>
  17. @foreach($errors->all()as$error)
  18. <li>{{$error}}</li>
  19. @endforeach
  20. </ul>
  21. </div>
  22. @endif
  23. {!! Form::model($product,['method'=>'PATCH','route'=>['productCRUD.update',$product->id]])!!}
  24. @include('ProductCRUD.form')
  25. {!! Form::close()!!}
  26. @endsection
@extends('layouts.default') @section('content')    <div >        <div >            <div >                <h2>Edit Product</h2>            </div>            <div >                <a  href="{{ route('productCRUD.index') }}"> Back</a>            </div>        </div>    </div>    @if (count($errors) > 0)        <div >            <strong>Whoops!</strong> There were some problems with your input.<br><br>            <ul>                @foreach ($errors->all() as $error)                    <li>{{ $error }}</li>                @endforeach            </ul>        </div>    @endif    {!! Form::model($product, ['method' => 'PATCH','route' => ['productCRUD.update', $product->id]]) !!}        @include('ProductCRUD.form')    {!! Form::close() !!}@endsection

Now we create a new blade file form.blade.php within ProductCRUD folder

resources/views/ProductCRUD/form.blade.php

  1. <divclass="row">
  2. <divclass="col-xs-12 col-sm-12 col-md-12">
  3. <divclass="form-group">
  4. <strong>Name:</strong>
  5. {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
  6. </div>
  7. </div>
  8. <divclass="col-xs-12 col-sm-12 col-md-12">
  9. <divclass="form-group">
  10. <strong>Details:</strong>
  11. {!! Form::textarea('details', null, array('placeholder' => 'Details','class' => 'form-control','style'=>'height:100px')) !!}
  12. </div>
  13. </div>
  14. <divclass="col-xs-12 col-sm-12 col-md-12 text-center">
  15. <buttontype="submit"class="btn btn-primary">Submit</button>
  16. </div>
  17. </div>
<div >        <div >            <div >                <strong>Name:</strong>                {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}            </div>        </div>        <div >            <div >                <strong>Details:</strong>                {!! Form::textarea('details', null, array('placeholder' => 'Details','class' => 'form-control','style'=>'height:100px')) !!}            </div>        </div>        <div >                <button type="submit" >Submit</button>        </div>    </div>

At Last we create a blade file to show the product details

resources/views/ProductCRUD/show.blade.php

  1. @extends('layouts.default')
  2. @section('content')
  3. <divclass="row">
  4. <divclass="col-lg-12 margin-tb">
  5. <divclass="pull-left">
  6. <h2> Show Product</h2>
  7. </div>
  8. <divclass="pull-right">
  9. <aclass="btn btn-primary"href="{{ route('productCRUD.index') }}"> Back</a>
  10. </div>
  11. </div>
  12. </div>
  13. <divclass="row">
  14. <divclass="col-xs-12 col-sm-12 col-md-12">
  15. <divclass="form-group">
  16. <strong>Name:</strong>
  17. {{ $product->name}}
  18. </div>
  19. </div>
  20. <divclass="col-xs-12 col-sm-12 col-md-12">
  21. <divclass="form-group">
  22. <strong>Details:</strong>
  23. {{ $product->details}}
  24. </div>
  25. </div>
  26. </div>
  27. @endsection
@extends('layouts.default') @section('content')    <div >        <div >            <div >                <h2> Show Product</h2>            </div>            <div >                <a  href="{{ route('productCRUD.index') }}"> Back</a>            </div>        </div>    </div>    <div >        <div >            <div >                <strong>Name:</strong>                {{ $product->name}}            </div>        </div>        <div >            <div >                <strong>Details:</strong>                {{ $product->details}}            </div>        </div>    </div>@endsection

Now you can build your first CRUD Application..

Show Demo

Label :

PHP

Laravel PHP Framework

MVC

Web Development

Hope this code and post will helped you for implement Laravel 5.2 CRUD (Create Read Update Delete) Example from Scratch. 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 code 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 *

  +  27  =  37

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