AppDividend
Latest Code Tutorials

Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch

77

Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch is today’s leading topic. Laravel 5.7 has some new cool features as well as several other enhancement and bug fixes. In previous Laracon event, Taylor Otwell announced some of the notable changes which are the following.

  1. Resources Directory Changes.
  2. Callable Action URLs.
  3. Laravel Dump Server.
  4. Improved Error Messages For Dynamic Calls.

Now in this tutorial, first we will install the Laravel 5.7 and then build a CRUD application.

Content Overview

Laravel 5.7 CRUD Example Tutorial

First, let us install Laravel 5.7 using the following command. We will use Composer Create-Project to generate laravel 5.7 projects.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

#1: Install Laravel 5.7

Type the following command. Make sure you have installed composer in your machine.

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

 

Laravel 5.7 CRUD Example Tutorial

Okay, now go inside the folder and install the npm packages using the following command. The requirement for the below command is that node.js is installed on your machine. So, if you have not installed, then please install it using its official site.

npm install

#2: Configure MySQL Database

Now, first, in MySQL, you need to create the database, and then we need to connect that database to the Laravel application. You can also use phpmyadmin to create the database.

Now, After creating the database, we need to open the .env file inside Laravel stocks project and add the database credentials. I have typed my credentials; please enter yours otherwise it won’t connect.

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

So now you will be able to connect the MySQL database.

Laravel always ships with migration files, so you can able to generate the tables in the database using the following command.

php artisan migrate

 

Laravel 5.7 Tutorial

#3: Create a model and migration file.

Go to the terminal and type the following command to generate the model and migration file.

php artisan make:model Share -m

It will create the model and migration file. Now, we will write the schema inside <timestamp>create_shares_table.php file.

   /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('shares', function (Blueprint $table) {
            $table->increments('id');
            $table->string('share_name');
            $table->integer('share_price');
            $table->integer('share_qty');
            $table->timestamps();
        });
    }

Okay now migrate the table using the following command.

php artisan migrate

Now, add the fillable property inside Share.php file.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Share extends Model
{
  protected $fillable = [
    'share_name',
    'share_price',
    'share_qty'
  ];
}

#4: Create routes and controller

First, create the ShareController using the following command.

php artisan make:controller ShareController --resource

Now, inside routes >> web.php file, add the following line of code.

<?php

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

Route::resource('shares', 'ShareController');

Actually, by adding the following line, we have registered the multiple routes for our application. We can check it using the following command.

php artisan route:list

 

Laravel 5.7 Example

Okay, now open the ShareController.php file, and you can see that all the functions declarations are there.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

#5: Create the views

Inside resources >> views folder, create one folder called shares.

Inside that folder, create the following three files.

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

But inside views folder, we also need to create a layout file. So create one file inside the views folder called layout.blade.php. Add the following code inside the layout.blade.php file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Laravel 5.7 CRUD Example Tutorial</title>
  <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
  <div class="container">
    @yield('content')
  </div>
  <script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>

So basically this file is our main template file, and all the other view files will extend this file. Here, we have already included the bootstrap four by adding the app.css.

Next step would be to code the create.blade.php file. So write the following code inside it.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Share
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('shares.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Share Name:</label>
              <input type="text" class="form-control" name="share_name"/>
          </div>
          <div class="form-group">
              <label for="price">Share Price :</label>
              <input type="text" class="form-control" name="share_price"/>
          </div>
          <div class="form-group">
              <label for="quantity">Share Quantity:</label>
              <input type="text" class="form-control" name="share_qty"/>
          </div>
          <button type="submit" class="btn btn-primary">Add</button>
      </form>
  </div>
</div>
@endsection

Okay, now we need to open the ShareController.php file, and on the create function, we need to return a view, and that is the create.blade.php file.

// ShareController.php

public function create()
{
   return view('shares.create');
}

Save the file and start the Laravel development server using the following command.

php artisan serve

Go to the http://localhost:8000/shares/create. 

You can see something like this.

 

Laravel 5.7 Demo For Beginners

#6: Save the data

Now, we need to code the store function to save the data in the database. First, include the Share.php model inside ShareController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Share;

class ShareController 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('shares.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);
      $share = new Share([
        'share_name' => $request->get('share_name'),
        'share_price'=> $request->get('share_price'),
        'share_qty'=> $request->get('share_qty')
      ]);
      $share->save();
      return redirect('/shares')->with('success', 'Stock has been added');
    }

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

If the validation fails, then it will throw an error, and we will display inside the create.blade.php file.

If all the values are good and pass the validation, then it will save the values in the database.

 

Laravel 5.7 CRUD

#7: Display the data.

Okay, now open the file called index.blade.php file and add the following code.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="uper">
  @if(session()->get('success'))
    <div class="alert alert-success">
      {{ session()->get('success') }}  
    </div><br />
  @endif
  <table class="table table-striped">
    <thead>
        <tr>
          <td>ID</td>
          <td>Stock Name</td>
          <td>Stock Price</td>
          <td>Stock Quantity</td>
          <td colspan="2">Action</td>
        </tr>
    </thead>
    <tbody>
        @foreach($shares as $share)
        <tr>
            <td>{{$share->id}}</td>
            <td>{{$share->share_name}}</td>
            <td>{{$share->share_price}}</td>
            <td>{{$share->share_qty}}</td>
            <td><a href="{{ route('shares.edit',$share->id)}}" class="btn btn-primary">Edit</a></td>
            <td>
                <form action="{{ route('shares.destroy', $share->id)}}" method="post">
                  @csrf
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </tbody>
  </table>
<div>
@endsection

Next thing is we need to code the index() function inside ShareController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Share;

class ShareController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $shares = Share::all();

        return view('shares.index', compact('shares'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);
      $share = new Share([
        'share_name' => $request->get('share_name'),
        'share_price'=> $request->get('share_price'),
        'share_qty'=> $request->get('share_qty')
      ]);
      $share->save();
      return redirect('/shares')->with('success', 'Stock has been added');
    }

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

#8: Edit and Update Data

First, we need to code the edit() function inside  ShareController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Share;

class ShareController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $shares = Share::all();

        return view('shares.index', compact('shares'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);
      $share = new Share([
        'share_name' => $request->get('share_name'),
        'share_price'=> $request->get('share_price'),
        'share_qty'=> $request->get('share_qty')
      ]);
      $share->save();
      return redirect('/shares')->with('success', 'Stock has been added');
    }

    /**
     * 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)
    {
        $share = Share::find($id);

        return view('shares.edit', compact('share'));
    }

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

Now, add the following lines of code inside the edit.blade.php file.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Edit Share
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('shares.update', $share->id) }}">
        @method('PATCH')
        @csrf
        <div class="form-group">
          <label for="name">Share Name:</label>
          <input type="text" class="form-control" name="share_name" value={{ $share->share_name }} />
        </div>
        <div class="form-group">
          <label for="price">Share Price :</label>
          <input type="text" class="form-control" name="share_price" value={{ $share->share_price }} />
        </div>
        <div class="form-group">
          <label for="quantity">Share Quantity:</label>
          <input type="text" class="form-control" name="share_qty" value={{ $share->share_qty }} />
        </div>
        <button type="submit" class="btn btn-primary">Update</button>
      </form>
  </div>
</div>
@endsection

Finally, code the update function inside ShareController.php file.

public function update(Request $request, $id)
{
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);

      $share = Share::find($id);
      $share->share_name = $request->get('share_name');
      $share->share_price = $request->get('share_price');
      $share->share_qty = $request->get('share_qty');
      $share->save();

      return redirect('/shares')->with('success', 'Stock has been updated');
}

So, now you can update the existing values.

#9: Delete the data

Just code the delete function inside ShareController.php file.

public function destroy($id)
{
     $share = Share::find($id);
     $share->delete();

     return redirect('/shares')->with('success', 'Stock has been deleted Successfully');
}

Finally, Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch is over. I have put the code in the Github Repo. So check out as well.

Github Code

77 Comments
  1. Calvin Carlos da Conceição Chiulele says

    Nice tutorial. Thanks for you sharing!

    1. Krunal says

      Thanks man

      1. Jephte says

        Wonderful tutorial Krunal. Thank you very much.

    2. Aqib Ali says

      thank you so much nice tutorial

  2. Yusup Supriatna says

    Your tutorial is very good . Thanks for you sharing

  3. Yusup Supriatna says

    I’m so sorry but can you help me please , I’ve error in ShareController :
    public function create()
    {
    return view(‘shares.create’);
    }

    shares.create not found

    1. Umair Khalid says

      check that your create shares folder in views folder

    2. nico says

      same error I fixed only leave
      public function create()
      {
      return view(‘create’);
      }

    3. shahidulmostafa@gmail.com says

      layout.blade.php file create in view folder. not a shares folder.
      resources/views/layout.blade.php

      1. Agung says

        thank you !

    4. Elijah says

      You should add this one below line 5 of sharecontroller.php

      use App\Share;

  4. Jephte says

    What is the error? 404. Maybe your forgot the “s” in “Route::resource(‘shares’, ‘ShareController’);” inside the web.php.

  5. Mark Zuckerberg says

    /shares/create doesn’t show anything, blank page

    1. Kurabiron says

      Had the same problem, but something was wrong in my create.blade.php file

  6. William says

    Hi,
    I have an Error while running php artisan migrate command PDOException::(“could not find driver”)
    please help me anyone.

    1. Marcin says

      apt-get install php7.x-mysql

      make sure that you have enabled pdo extension ( you can check it at phpinfo() )

      in php.ini

      ;extension=php_pdo_mysql.so
      Change it to this

      extension=pdo_mysql.so

      restart apache2/nginx

  7. GuntherWyns says

    Hello

    Can somebody help me?

    Missing required parameters for [Route: shares.edit] [URI: shares/{share}/edit]. (View: C:\wamp64\www\stocks\resources\views\shares\index.blade.php)

    Missing required parameters for [Route: {$route->getName()}] [URI: {$route->uri()}]

  8. lamhaison says

    Thank you so much because of making a good tutorial.

  9. SD says

    Hello, I am trying to get a problem, giving an exception, when I enter localhost: 8000 / shares / create

    ErrorException (E_ERROR)
    View [layout] not found. (View: C: \ laravel \ resources \ views \ shares \ create.blade.php)

    \vendor\laravel\framework\src\Illuminate\View\FileViewFinder.php137

    How can I solve it please

  10. Emmanuel says

    Is a nice tutorial but i have an the following error: InvalidArgumentException
    View [shares.create] not found.how can i fix it anyway?

  11. Nagesh says

    Very nice tutorial. Thank you very much

  12. Jeffrey Del Rosario says

    do we really need to use npm?

    1. Krunal says

      For this example, I would say no, but in general Laravel project yes because you generally use your own JS scripts.

      1. seema says

        hello sir your coding is so easy plz share barcode generation in laravel 5.7. When i submit product in database ,barcode is generate for submitted product.

  13. Wahad says

    best tutorial ever.. thank you as always

  14. neriosoft says

    pls i am having this error:

    InvalidArgumentException
    View [shares.create] not found.

    1. nico says

      try return view(‘create’);

  15. DR NIKHIL KUMAR GHORAI says

    A very nice tutorial. i had haunting a written guide than a video tutorial. Ultimately got it.Thanks a lot

  16. DR NIKHIL KUMAR GHORAI says

    A nice tutorial. I think a gem article for laravel 5.7 . The scripts are very consized and well written.
    I was haunting for a month for the right codes. Ultimately got here. Thanks a lot. keep helping us who are hobbiest programmer and learning ownself from illustrations in internet.

  17. Roshan says

    Dear Kunal, can post a tutorials how to create a CRUD page Ex; About us ( Title, Body and Image ) all I’ve seen every where is how to do post with post controllers. I want to do a blog with generic pages with edit and publish functions. Can you please share this. I’m following your great tutorials.

  18. Alfonso says

    awesome tutorial, thanks!

  19. mohsin ali says

    good work dear, thanks alot

  20. alam says

    I have to make add button to be able create new item, ..

  21. Joseph Gitahi says

    I very precise and informative code. I like the spirit sir

  22. MimisK says

    i love you! <3

  23. MimisK says

    i love you <3

  24. dhananjay says

    best
    don’t have word for you man,
    save my life

  25. Nomie says

    Thanks a lot bro. This really helped me out. i would really be very thankful if u suggest how can i improve in laravel further.

  26. faysal shema says

    thx for ur tutorials

  27. nivea says

    it is very interesting laravel !
    thank you so much

  28. DANIMU says

    what if one of the input are dropdown? how to get the value in the controller?

  29. Héctor Pérez Silva says

    Works like a charm

  30. elmizan says

    awesome

  31. Zam says

    Awesome! Compact and practical

  32. danish says

    Awesome !! thank you so much

  33. Muhammad Waleed says

    Extremely stunning now CRUD is like a piece of cake for me. Tons of thanks from PAKISTAN

  34. afshin says

    hi
    i do all steps but dont works for me
    show me this error !
    (1/1) TokenMismatchException

    1. Krunal says

      You need to add @csrf field inside the form. It’s CSRF exception.

      1. afshin says

        i add @csrf
        but print @csrf;
        and dont do anything

        1. Bradley Bourn says

          Update Laravel to >= 5.6

  35. najah says

    hi
    i do all steps but dont works for me
    show me this error !
    (1/1) BadMethodCallException
    Method validate does not exist.

  36. Fachry Nurdiansyah says

    Thanks man, you really helped me a lot!

  37. amir says

    thanks a lot master , this is my First project

  38. Patrick says

    Getting problems with the index and edit files because of the following error

    ErrorException (E_WARNING)
    array_merge(): Expected parameter 2 to be an array, string given

  39. Robin singh says

    Why you creating form while delete the record. is it good or we can pass id as it is like edit

  40. Amit Kumar says

    Undefined variable: student (View: E:\xampp\htdocs\blog\resources\views\students\edit.blade.php)

    Here I am getting an error i.e undefined variable student. I am using Student instead of share.
    Tell me how you are getting $share reference in edit.blade.php because you are not declaring anywhere.
    This is happening when I am clicking on the edit link.

    1. walter P Rincon says

      you have to change “share.php” in folder providers to export class student instead of share

  41. Mukesh says

    such a nice tutorial….

  42. Agung says

    at number #3, should add options -mcr, so the controller and resource also created automatically

  43. Gerry Powa says

    Nice tutorial (y).. Thanks for sharing

  44. Venis says

    Thank You Very Much. Great Tutorial

  45. Senduran Ravikumar says

    it is an awesome tutorial

  46. rihana says

    heyyy thanks man

  47. wilson says

    Hola desde Chile

    Excelente tutorial muchas gracias muy bien estructura y explicado, Gracias por tener la humildad de enseñar. Seria bueno que siguiera con el Login y los ACL.

    Felicitaciones…

    Muchas gracias

  48. Ben Miles says

    Excellent tutorial, helpful and well-written.

    I wanted to point out a typo that I found that caused me some errors. In step #8, in the code for edit.blade.php, the “value” attributes of your three inputs are not wrapped in quotation marks. This causes the “edit” view to only show the first word of each string, and prevents successful updates.

  49. TARAK VIJAY SAWANT says

    Hi, I have Successfully solved my bug referring your tutorial. However I had a doubt that can we excecute arithmetic operations like sum of data in rows in one block

  50. Doni says

    I was looking for simple tutorial like this. It is a good introductory for new comers to laravel thank you very much

  51. Martin says

    Hi, im share this like a retribution:
    if you need take out the welcome view, replace this :

    Route::get(‘/’, function () {
    return view(‘welcome’);
    });

    For this:

    Route::get(‘/’, ‘ShareController@index’)->name(‘index’);
    Route::resource(‘shares’, ‘ShareController’);

    Great Tutorial
    Thank You Very Much.

  52. Riku says

    Thank you for such a nice simple tutorial

  53. Vishnu Detroja says

    Nice tutorial. This is very usefull for me. Thanks for you sharing!

  54. Vishnu Detroja says

    This is very usefull for me. Thanks for you sharing!

  55. Admoo Finance says

    in edit.blade.php @method(‘PATCH’) should be @method(‘PUT’)

  56. Yong says

    Class ‘App\Http\Controllers\Share’ not found…Help me solve this…

    1. Krunal says

      Add App\Share at the start of the controller.

  57. Renz says

    OMG, thank you for this. I like you <3

  58. Fahad says

    Really great tutorial. Saved my time. Thank you for this.

  59. megha says

    i’m getting this error please help me i’m new to laravel
    Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
    Class ‘App\Performance’ not found

Leave A Reply

Your email address will not be published.

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