Laravel 5.4 Crud Example: The Complete Guide

Here are the steps to create a crud application in Laravel.

Step 1: Create a Laravel project

Type the following command in your terminal to create a project.

composer create-project --prefer-dist laravel/laravel Laravel54

It will take 2 minutes to install a brand-new Laravel Framework

After installing, go to your project root folder and type php artisan serve in the terminal; your project URL might look like this

http://localhost:8000

Now open that laravel project folder in your favorite editor.

Step 2: Edit the .env file for database configuration

In your project root folder, there is a file called .env, which we need to edit to set up a database configuration. I am using the MySQL database.

// .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel54
DB_USERNAME=root
DB_PASSWORD=mysql

Step 3: Use migrations provided by laravel to create users and password_resets table

Now go to the terminal, and run the following command

php artisan migrate

If you have created the database in MySQL and you have provided the correct credentials to the .env file, then you will see there are three tables generated in the MySQL database.

Step 4: Create a controller file for our CRUD operations.

Go to the terminal, and type the following command in your root project.

php artisan make:controller CRUDController --resource

Now go to laravel54 > app > Http > Controllers. You will see the CRUDController file in that folder.

This file has all the boilerplate needed for our Crud operations.

Step 5: Create a model file for CRUD operations.

In the terminal, type the following command in your root project.

php artisan make:model Crud -m

This command will also create a migration file for our CRUD operations.

Step 6: Edit the crud migration file and create the required fields for the database.

The migration file is located in the laravel54 > database > migrations folder.

<?php
// create_cruds_table

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

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

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

Run the following command in your terminal.

php artisan migrate

Step 7: Create views for setting up a form

Go to laravel54 > resources > views . Locate into that folder and then create a master view called master.blade.php. A blade is a templating engine used by laravel.

<!-- master.blade.php -->

<!doctype html>
<html lang="{{ config('app.locale') }}">
    <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>CRUD Operations</title>

        <!-- Fonts -->
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <br><br>
        @yield('content')
    </body>
</html>

Now create a new folder inside the views directory called crud. Go inside that folder and create the following files

  1. index.blade.php
  2. create.blade.php
  3. edit.blade.php

Step 8: Create a form in create.blade.php

<!-- create.blade.php -->

@extends('master')
@section('content')
<div class="container">
  <form>
    <div class="form-group row">
      <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label>
      <div class="col-sm-10">
        <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title">
      </div>
    </div>
    <div class="form-group row">
      <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label>
      <div class="col-sm-10">
        <textarea name="post" rows="8" cols="80"></textarea>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-md-2"></div>
      <input type="submit" class="btn btn-primary">
    </div>
  </form>
</div>
@endsection

Step 9: Setup a route for the request handling.

Go to the routes > web.php

<?php

Route::get('/', function () {
    return view('welcome');
});
Route::resource('crud', 'CRUDController');

Here we have added a resource route, and all the functions reside in app > Http > controllers > CRUDController.

Step 10: Edit CRUDController File

// CRUDController.php

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

Here we have to return the view when the request hits the route; it will be redirected to this controller’s create method. So our view should be accessible via the following URL in the form.

http://localhost:8000/crud/create

We are now able to see the form with the two fields.

Step 11: Add the CSRF token and set the post route of the form.

<!-- create.blade.php -->

@extends('master')
@section('content')
<div class="container">
  <form method="post" action="{{url('crud')}}">
    <div class="form-group row">
      {{csrf_field()}}
      <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label>
      <div class="col-sm-10">
        <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title">
      </div>
    </div>
    <div class="form-group row">
      <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label>
      <div class="col-sm-10">
        <textarea name="post" rows="8" cols="80"></textarea>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-md-2"></div>
      <input type="submit" class="btn btn-primary">
    </div>
  </form>
</div>
@endsection

We have put the {{csrf_field()}} in the form so that malicious attacks can not harm our web application.

Step 12: Code the store function and use the Crud model to insert the data

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Crud;

class CRUDController 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()
    {
        return view('crud.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $crud = new Crud([
          'title' => $request->get('title'),
          'post' => $request->get('post')
        ]);

        $crud->save();
        return redirect('/crud');
    }

    /**
     * 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)
    {
        //
    }
}

Here we need to create a protected field called $fillable in the Crud model. Otherwise, it will throw a mass assignment exception.

// Crud.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Crud extends Model
{
    protected $fillable = ['title','post'];
}

When you fill in the title and post field in our form and submit the form, the new entry will be added to the database. We can confirm it by following the steps.

Step 13: Code index() function in the CRUDController File.

//CrudController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Crud;

class CRUDController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cruds = Crud::all()->toArray();
        
        return view('crud.index', compact('cruds'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $crud = new Crud([
          'title' => $request->get('title'),
          'post' => $request->get('post')
        ]);

        $crud->save();
        return redirect('/crud');
    }

    /**
     * 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)
    {
        //
    }
}

Step 14: Need to update index.blade.php

<!-- index.blade.php -->
@extends('master')
@section('content')
  <div class="container">
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Post</th>
      </tr>
    </thead>
    <tbody>
      @foreach($cruds as $post)
      <tr>
        <td>{{$post['id']}}</td>
        <td>{{$post['title']}}</td>
        <td>{{$post['post']}}</td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
@endsection

Next, shoot the following URL.

http://localhost:8000/crud

You will see a table that has the id, title, and post-column with their respective data.

Step 15: Add Edit and Delete Button in the index.blade.php

<!-- index.blade.php -->

@extends('master')
@section('content')
  <div class="container">
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Post</th>
        <th colspan="2">Action</th>
      </tr>
    </thead>
    <tbody>
      @foreach($cruds as $post)
      <tr>
        <td>{{$post['id']}}</td>
        <td>{{$post['title']}}</td>
        <td>{{$post['post']}}</td>
        <td><a href="{{action('CRUDController@edit', $post['id'])}}" class="btn btn-warning">Edit</a></td>
        <td><a href="{{action('CRUDController@destroy', $post['id'])}}" class="btn btn-danger">Delete</a></td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
@endsection

Step 16: Create an edit function to pass the data to the edit view.

<?php

// CRUDController.php  
/**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $crud = Crud::find($id);
        
        return view('crud.edit', compact('crud','id'));

    }

Step 17: Create an edit view.

<!-- edit.blade.php -->

@extends('master')
@section('content')
<div class="container">
  <form method="post" action="{{action('CRUDController@update', $id)}}">
    <div class="form-group row">
      {{csrf_field()}}
       <input name="_method" type="hidden" value="PATCH">
      <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label>
      <div class="col-sm-10">
        <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title" value="{{$crud->title}}">
      </div>
    </div>
    <div class="form-group row">
      <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label>
      <div class="col-sm-10">
        <textarea name="post" rows="8" cols="80">{{$crud->post}}</textarea>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-md-2"></div>
      <button type="submit" class="btn btn-primary">Update</button>
    </div>
  </form>
</div>
@endsection

Here we have used one more hidden field called the _method, a PATCH request to the server to update the data very quickly.

Step 18: Code update() in the CRUDController.

<?php
// CRUDController.php

 /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $crud = Crud::find($id);
        $crud->title = $request->get('title');
        $crud->post = $request->get('post');
        $crud->save();
        return redirect('/crud');
    }

After filling the update form, we can see on the index page that our data is updated. So now only Delete functionality is remaining.

Step 19: Create a delete form to delete the data.

<!-- index.blade.php -->

@extends('master')
@section('content')
  <div class="container">
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Post</th>
        <th colspan="2">Action</th>
      </tr>
    </thead>
    <tbody>
      @foreach($cruds as $post)
      <tr>
        <td>{{$post['id']}}</td>
        <td>{{$post['title']}}</td>
        <td>{{$post['post']}}</td>
        <td><a href="{{action('CRUDController@edit', $post['id'])}}" class="btn btn-warning">Edit</a></td>
        <td>
          <form action="{{action('CRUDController@destroy', $post['id'])}}" method="post">
            {{csrf_field()}}
            <input name="_method" type="hidden" value="DELETE">
            <button class="btn btn-danger" type="submit">Delete</button>
          </form>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
@endsection

Step 20: Code the destroy() method in the CRUDController.

<?php
// CRUDController.php

/**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
      $crud = Crud::find($id);
      $crud->delete();

      return redirect('/crud');
    }

In the delete functionality, we have not put any confirm box, but it is okay for the demo. So I want you to take this demo and see how the laravel’ flow is working.

Output

Laravel 5.4 Crud Example From Scratch
Laravel 5.4 Crud Example From Scratch

There is some routes list in the resource controller. Type in the terminal: php artisan route:list

$ php artisan route:list
+--------+-----------+------------------+--------------+---------------------------------------------+--------------+
| Domain | Method    | URI              | Name         | Action                                      | Middleware   |
+--------+-----------+------------------+--------------+---------------------------------------------+--------------+
|        | GET|HEAD  | /                |              | Closure                                     | web          |
|        | GET|HEAD  | api/user         |              | Closure                                     | api,auth:api |
|        | GET|HEAD  | crud             | crud.index   | App\Http\Controllers\CRUDController@index   | web          |
|        | POST      | crud             | crud.store   | App\Http\Controllers\CRUDController@store   | web          |
|        | GET|HEAD  | crud/create      | crud.create  | App\Http\Controllers\CRUDController@create  | web          |
|        | GET|HEAD  | crud/{crud}      | crud.show    | App\Http\Controllers\CRUDController@show    | web          |
|        | PUT|PATCH | crud/{crud}      | crud.update  | App\Http\Controllers\CRUDController@update  | web          |
|        | DELETE    | crud/{crud}      | crud.destroy | App\Http\Controllers\CRUDController@destroy | web          |
|        | GET|HEAD  | crud/{crud}/edit | crud.edit    | App\Http\Controllers\CRUDController@edit    | web          |

If you are curious how resource controller works behind the scenes, then this is your answer.

Github: https://github.com/KrunalLathiya/Laravel54

Steps to use Github code

  1. Clone the repo in your local.
  2. Go to the root of the project and run the command “composer update.
  3. Edit the .env file and use your MySQL database credentials.
  4. Run the command “php artisan migrate.
  5. Now, we need to bootstrap the Laravel server, so run “php artisan serve.
  6. If now, go to this URL: http://localhost:8000/crud/create.

87 thoughts on “Laravel 5.4 Crud Example: The Complete Guide”

  1. hello sir i am new in laravel 5.4. I downloaded your project from github and when running your project gives an error “(1/1) NotFoundHttpException
    in RouteCollection.php (line 179)” . i din’t modified any code just setup database connection.

    Reply
  2. Thans a lot for this tutorial! I follow all of the steps but using diferent data ( a books table with ISBN title and Author fields) and I got all results OK You´re MASTER. Thanks again
    Mauro Martin from Colombia

    Reply
  3. Hello Krunal I have same like this bt i am not getting the the view first of it was like blank page even i have added the source as you have mentioned after that it is displaying object not found.

    I want to thank you for making these for beginners like me it is easy to use..

    Reply
    • Actually, we can go with both approaches. IF only CRUD operations are there then we definitely go with controller file but if there is more logic behind any of the modules then we can go with models. Also, some folks create services file and in that they write queries. So whatever approach suits to your application but make sure that if you are working in a team then all follow the same convention and flow.

      Reply
  4. sir, i have getting the error “Warning: require(C:\xampp\htdocs\Lvl54CRUD\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Lvl54CRUD\bootstrap\autoload.php on line 17

    Fatal error: require(): Failed opening required ‘C:\xampp\htdocs\Lvl54CRUD\bootstrap/../vendor/autoload.php’ (include_path=’.;C:\xampp\php\PEAR’) in C:\xampp\htdocs\Lvl54CRUD\bootstrap\autoload.php on line 17”
    when i run your CRUD code…
    pls reply…

    Reply
  5. After step 14 , i get this error

    (1/1) FatalErrorException
    Class ‘AppHttpControllersCrud’ not found
    in CRUDController.php (line 16)

    Reply
  6. sir I have problem with the database
    when I create title and post then the information doesnt enter the database
    how i can solve this problem?
    Thanks for your help

    Reply
  7. After step 14, i get the error ErrorException
    Undefined variable: cruds (View: ..\resources\views\crud\index.blade.php)

    Reply
    • have you wrote this function in CRUDController,

      /**
      * Display a listing of the resource.
      *
      * @return IlluminateHttpResponse
      */
      public function index()
      {
      $cruds = Crud::all()->toArray();

      return view(‘crud.index’, compact(‘cruds’));
      }

      Reply
  8. Hi,
    After 18 th step I am getting error “MethodNotAllowedHttpException”, even it’s not coming inside update function.

    After google I came to know that this error might occur due to method type as in this update case it is PUT|PATCH. So what may be the cause of this issue. Any help

    Rest works fine for me.

    Thanks.

    Reply
  9. Hi. Thanks a lot for this one. This helps me a lot especially CRUD. Anyways my strength framework is codeigniter. Your code seems preety straigthforward and easy to understand.

    Reply
  10. Hi! I have been struggling for a while now. Please is there a way to create only an api with laravel without involving any form or anything? just an api that will interact with a mobile app. Thank you!

    Reply
    • Yes, you if you are using Laravel 5.4 then you can use api.php file in routes folder. Define all the routes specific to your mobile application needs and then call the http request like api/ products or api/product/create. You need to remember that you have to always put a prefix api for every routes in api.php file.

      Reply
  11. I will right away take hold of your rss feed as I can not to find your e-mail subscription link or newsletter service. Do you have any? Kindly allow me realize so that I may subscribe. Thanks.

    Reply
  12. Nice guide. I am getting this error midway through it though

    (1/1) FatalErrorException
    Class ‘App\Http\Controllers\Crud’ not found
    in CRUDController.php (line 16)

    Reply
  13. Let me rephrase it. Because I’ve already knew to run locally through public but I just want to know how to run it without through public folder. In other words, correct me if I’m wrong but it seems I have to set VH on public folder and root of live site on public folder as well, am I right?

    Reply
  14. Many Many Thanks For Providing Basic Knowledge of Laravel 5.4 with CRUD system in Detail.

    Now I have Learn many thing from that Example.
    Every code working properly.

    Thanks again.

    Reply
  15. Thank you for this post. I now have a good understanding of how MVC works in Laravel.
    I have xampp server and your crud application runs perfectly on my xampp server.
    This tutorial really helped me a lot!! Thank you

    Reply
  16. Hi Krunal

    really cool, but could you explain me the way data are stored in DB?
    From the form tha action say “{{url(‘crud’)}}”, so how it call the store function?

    Regards
    Alessandro

    Reply
  17. Hi Krunal,

    Thanks for the tutorial. I have doubt regarding the populating of form data. Support we provide state and city as dropdown, if a state is selected then the cities corresponding to the state should populate the dropdown menu. is it possible to provide so in laravel. Kindly advise

    Reply
  18. Really nice bro, but why it doesn’t work with XAMPP server? It only works with server of ‘php artisan serve’. XAMPP server give me ‘not found’ or ‘404’ for views. Why?

    Reply
  19. Hai sir, How about this coment in cmd when i working step 3,

    [Illuminate\Database\QueryException]
    SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: YES) (SQL: select * from informat
    ion_schema.tables where table_schema = laravel154 and table_name = migrations)

    Reply
  20. If you receive an SQL Error:
    “SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long;”

    Add to app/Providers/AppServiceProvider.php:
    -before class name
    use Illuminate\Support\Facades\Schema;
    -inside class
    public function boot()
    {
    Schema::defaultStringLength(191);
    }

    Reply
  21. One of the best Laravel CRUD post i have seen. Everything is working fine.
    Just add one Button New Post in index.blade.php which calls to CRUDController@create to achieve all functionality from one page.

    Reply
  22. Hi Krunal,
    Thank you so much for your helpful curd operation.

    Please solve my problem. when i edit data is not working proper its route is going in show function while submit data. please find below code.
    1.Edit file

    Back

    {{csrf_field()}}

    {{–
    ID
    id}}”>
    –}}

    Title
    title}}”>

    Description
    description}}”>

    Update

    2. This controller page
    public function show($id)
    {
    $read = blogs::findOrFail($id);
    return view(‘blogread’,compact(‘read’,’id’));
    }

    /**
    * Show the form for editing the specified resource.
    *
    * @param int $id
    * @return IlluminateHttpResponse
    */
    public function edit($id)
    {
    $editdata= blogs::find($id);
    return view(‘blogedit’, compact(‘editdata’,’id’));
    }

    /**
    * Update the specified resource in storage.
    *
    * @param IlluminateHttpRequest $request
    * @param int $id
    * @return IlluminateHttpResponse
    */
    public function update($id,Request $request)
    {
    $data= blogs::find($id);
    $data->title=$request->get(‘title’);
    $data->description=$request->get(‘description’);
    $data->save();
    return ‘data is updated’;

    }

    Reply
  23. hello,
    i have one error ocurs everytime in new project create and apply for php artisan migrate
    every time occur same error
    User table is already exits..
    so what can i do??

    Reply
  24. At step 11 you have given the form action url as action=”{{url(‘crud’)}}” but insert query is written in create function in crud controller . How did it worked? You didn’t mentioned the function name in form action.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.