AppDividend
Latest Code Tutorials

Laravel 5.6 CRUD Tutorial With Example

93,002

Get real time updates directly on you device, subscribe now.

Laravel 5.6 CRUD Tutorial is today’s leading topic. Laravel is a free, open-source PHP web framework.It follows MVC(Model View Controller) Architecture. Laravel is recognized as one of the most popular PHP frameworks. Bug fix releases 5.6 on February 7, 2018.Laravel become the first ever back-end framework to pass 40,000 stars on Github.In this tutorial, I will illustrate simple insert, update and delete application in Laravel 5.6 project. You have to just follow below step to create CRUD application in Laravel.I have listed the features of Laravel 5.6.

1)Logging Improvements

2)Single Server Task Scheduling

3)New Blade Directives

4)Bootstrap

5)API Controller Generation

6)Argon2 Password Hashing

7)UUID Methods

8)Dynamic Rate Limiting

9)Broadcast Channel Classes

10)Eloquent Date Casting

If you want to master in Laravel then check out this course. It has everything you want to know.
PHP with Laravel for beginners – Become a Master in Laravel

Laravel 5.6 CRUD Tutorial

We are going to make a simple system in which, we can register for the passport. It is a simple Laravel 5.6 crud application for starters. No big deal at all.

Step 1: Configure Laravel 5.6 Project.

Install the brand new Laravel Project by the typing following command.

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

Step 2: Setup a MySQL database in .env file.

Now, configure the database in the .env file.

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

I have set up local database credentials.

Next, migrate two tables provided by Laravel 5.6 Switch to your terminal and hit the following command.

php artisan migrate

It will build two tables in your database.

  1. users
  2. password_resets  

Step 3: Construct a model, migration file and controller for our Passports table.

Type the following command in your terminal.

php artisan make:model Passport -m

It will create two files.

Related Posts
1 of 39
  1. Passport.php model.
  2. create_passports_table migration file.

We need to create Schema for the passports table. So navigate to Laravel  >>  database  >>  migrations  >>  create_passports_table.

// create_passports_table
 public function up()
    {
        Schema::create('passports', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('date');
            $table->string('email')->unique();
            $table->integer('number');
            $table->string('office');
            $table->string('filename');
            $table->timestamps();
        });
    }

Now, migrate the table by the following command.

php artisan migrate

In the database, you can see the passports table.

Step 4: Build view file to add the Information in the database.

Create a file in the resources  >>  views  >>   create.blade.php and put the following code in it.

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel 5.6 CRUD Tutorial With Example  </title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet">  
    <script  data-src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>  
  </head>
  <body>
    <div class="container">
      <h2>Passport Appointment System</h2><br/>
      <form method="post" action="{{url('passports')}}" enctype="multipart/form-data">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Email">Email:</label>
              <input type="text" class="form-control" name="email">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Number">Phone Number:</label>
              <input type="text" class="form-control" name="number">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <input type="file" name="filename">    
         </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <strong>Date : </strong>  
            <input class="date form-control"  type="text" id="datepicker" name="date">   
         </div>
        </div>
         <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
                <lable>Passport Office</lable>
                <select name="office">
                  <option value="Mumbai">Mumbai</option>
                  <option value="Chennai">Chennai</option>
                  <option value="Delhi">Delhi</option>  
                  <option value="Bangalore">Bangalore</option>  
                </select>
            </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4" style="margin-top:60px">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
    </div>
    <script type="text/javascript">  
        $('#datepicker').datepicker({ 
            autoclose: true,   
            format: 'dd-mm-yyyy'  
         });  
    </script>
  </body>
</html>

Laravel 5.6 CRUD Operations

Step 5: Create one controller and route 

php artisan make:controller PassportController --resource

It will create one controller file called PassportController.php and It has all the CRUD Functions, we need to inquire.

we register one route in routes  >>  web.php file. So let us do it.

// web.php

Route::resource('passports','PassportController');

Now, turn to your terminal and type the next command.

php artisan route:list

Next step would be to go to PassportController.php file and add into create() function some code.

// PassportController.php

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

After that, we need to begin Laravel Development server. So in the terminal, follow the following command.

php artisan serve

Move to the browser and hit this URL: http://localhost:8000/passports/create

Step 6: Save Data into Database.

We require coding the store function in sequence to store the data in the database.

//PassportController.php
/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if($request->hasfile('filename'))
         {
            $file = $request->file('filename');
            $name=time().$file->getClientOriginalName();
            $file->move(public_path().'/images/', $name);
         }
        $passport= new \App\Passport;
        $passport->name=$request->get('name');
        $passport->email=$request->get('email');
        $passport->number=$request->get('number');
        $date=date_create($request->get('date'));
        $format = date_format($date,"Y-m-d");
        $passport->date = strtotime($format);
        $passport->office=$request->get('office');
        $passport->filename=$name;
        $passport->save();
        
        return redirect('passports')->with('success', 'Information has been added');
    }

Step 7: Make an index page to list the Information.

For that, front, we need to forward the data to the index.blade.php. So, in PassportController.php file, we need to write the code to retrieve the data and return it to the index view.

//PassportController.php

public function index()
    {
        $passports=\App\Passport::all();
        return view('index',compact('passports'));
    }

In resources >> views produce individual blade file called index.blade.php file and placed the subsequent code in it.

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index Page</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
    <br />
    @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Date</th>
        <th>Email</th>
        <th>Phone Number</th>
        <th>Passport Office</th>
        <th colspan="2">Action</th>
      </tr>
    </thead>
    <tbody>
      
      @foreach($passports as $passport)
      @php
        $date=date('Y-m-d', $passport['date']);
        @endphp
      <tr>
        <td>{{$passport['id']}}</td>
        <td>{{$passport['name']}}</td>
        <td>{{$date}}</td>
        <td>{{$passport['email']}}</td>
        <td>{{$passport['number']}}</td>
        <td>{{$passport['office']}}</td>
        
        <td><a href="{{action('PassportController@edit', $passport['id'])}}" class="btn btn-warning">Edit</a></td>
        <td>
          <form action="{{action('PassportController@destroy', $passport['id'])}}" method="post">
            @csrf
            <input name="_method" type="hidden" value="DELETE">
            <button class="btn btn-danger" type="submit">Delete</button>
          </form>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
  </body>
</html>

So, when you type the URL: http://localhost:8000/passports

Laravel 5.6 Example Tutorial

Step 8: Build an edit view for updating the Information.

Our step will be to join the edit function in PassportController.php file and set the following code in it.

//PassportController.php

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

Now, make an edit.blade.php file inside resources  >>  views

<!-- edit.blade.php -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel 5.6 CRUD Tutorial With Example </title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
      <h2>Edit A Form</h2><br  />
        <form method="post" action="{{action('PassportController@update', $id)}}">
        @csrf
        <input name="_method" type="hidden" value="PATCH">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name" value="{{$passport->name}}">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="email">Email</label>
              <input type="text" class="form-control" name="email" value="{{$passport->email}}">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="number">Phone Number:</label>
              <input type="text" class="form-control" name="number" value="{{$passport->number}}">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4" style="margin-left:38px">
                <lable>Passport Office</lable>
                <select name="office">
                  <option value="Mumbai"  @if($passport->office=="Mumbai") selected @endif>Mumbai</option>
                  <option value="Chennai"  @if($passport->office=="Chennai") selected @endif>Chennai</option>
                  <option value="Delhi" @if($passport->office=="Delhi") selected @endif>Delhi</option>  
                  <option value="Bangalore" @if($passport->office=="Bangalore") selected @endif>Bangalore</option>
                </select>
            </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4" style="margin-top:60px">
            <button type="submit" class="btn btn-success" style="margin-left:38px">Update</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

Next step would be to code the update function. I have not updated the following fields.

  1. Date
  2. Image

If you are taking this tutorial, then this is the task for you to complete this. I need you to complete this update module on yourself.

//PassportCpntroller.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)
    {
        $passport= \App\Passport::find($id);
        $passport->name=$request->get('name');
        $passport->email=$request->get('email');
        $passport->number=$request->get('number');
        $passport->office=$request->get('office');
        $passport->save();
        return redirect('passports');
    }

Step 9: Remove the Information.

//PassportController.php
/**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $passport = \App\Passport::find($id);
        $passport->delete();
        return redirect('passports')->with('success','Information has been  deleted');
    }

Finally, Our Laravel 5.6 CRUD Tutorial is over. Thanks for taking.

47 Comments
  1. NoobCoder says

    Hey, thanks for the tutorial, i really appreciated it. I’m new to php and laravel, I followed your tutorial but get caught in some error, it said this : Class ‘App\Http\Controllers\Passport’ not found, is the Passport model doesn’t need to be edited ? thanks.

    1. Krunal says

      You need to include the model like use AppPassport; inside Controller file And yes you need to create the model.

      1. Brian says

        How is that one done???

        1. A says

          put
          use App\Passport;
          in
          class PassportController extends Controller
          thats all

          Passport.php can be empty

          1. Riyaz says

            Thanks A.

            I know it was the just small error, but I am just new in Laravel.

        2. Kamran says

          i am stuck in this problem can anyone plz elaborate

          1. Fian says

            me too.. stuck in this problem.
            already put App\Passport; inside Controller Passport
            and “Class ‘App\Http\Controllers\Passport’ not found”

          2. Krunal says

            Actually, you need to put AppPassport; at the starting of the file, not inside any function, but nevermind, I have updated this tutorial.

  2. Noe says

    Hallo thanks for the tutorial. When I was in the step 5 and type php artisan serve, in cmd said: 127.0.0.1:50456 Invalid request (Unexpected EOF) and when I type URL: http://localhost:8000/passports/create, browser said : Sorry, the page you are looking for could not be found. Would you tell me where I am miss and how I solve the problem, Thanks

  3. tizi says

    created an authentication with email notification laravel tutorial

  4. rodney villareal says

    This is so helpful. Thanks

    Do you have sample registration form with login form sir?

  5. Bruno says

    How could i make the index page the home page? I’m trying but i could’n figure it out a good way to pass the passports agument with the page

  6. Felix Labayen says

    Hi Krunal,

    Thanks for your tutorial.
    It is working and I learn a lot.
    By the way, regarding storing uploaded images, you can do it in one line of code
    like this:

    $file = $request->file(‘filename’)->store(‘myTestStorage’);

    Then on saving to database:

    $passport->filename = $file;

    The file will be stored in yourapp/storage/app/myTestStorage

  7. Luiz says

    Hello Krunal. Congratulations for your iniative. I couldn´t pass through step 3.
    After add the “Schema::create(‘passports’, fun…”, i got an error when i tried the command “php artisan migrate”, cause we had used this command once before with other tables. How do we proceed? Thanks.

    1. Luiz says

      Problem solved.

  8. hiren says

    Hello there
    i am new in laravel i getting this “TokenMismatchException” error while update and delete operation
    can you please help me

  9. JP says

    Will only create CRUD in Step 5 (PassportController) when you add the –resource command like so:

    php artisan make:controller PassportController –resource

    1. Krunal says

      Yes, it will help us to build CRUD operations easily. It will create some boilerplate for us to do CRUD.

  10. Ramadan says

    Fam I love u I was stuck on editing my table for a long time till I came across this tutorial… You are blessed

  11. Leirax says

    Hey your tutorias was good but i got some error TokenMismatchException

    1. Krunal says

      please include @csrf inside your forms.

  12. Surekha says

    Hi, I am following your tutorial. And at step 3 it couldn’t create a file Passport.php, only creates create_passports_table.

    Also it creates file name with prefix of current date and some number e.g.
    2018_05_14_145850_create_passports_table.php

    How can I create filename with only letters e.g create_passports_table.php

    Thanks

  13. Hasan says

    Could you please guide me the date and image section also in edit.balde.php?

  14. Tyra says

    Hi, I am following your tutorial. In Step 5: Create one controller and route i don’t understand clearly.

    Firstly, I already create one controller file called PassportController.php, it there compulsary to add “–resource” after type in terminal command php artisan make:controller PassportController???

    Secondly, register one route in routes >> web.php file. where mus i put the web.php file? in what folder ?

    1. Krunal says

      No that is not compulsory to create additional resource flag. It is just useful when we deal with CRUD operations. By means of creating a route is inside the web.php file, you need to define one route. There is already a web.php file. We just need to add different routes.

      1. Tyra says

        i have error TokenMismatchException in VerifyCsrfToken.php line 67:

        how to include @csrf? can u show to me? im new in laravel. pleaseeeee!!!!!!!

        1. Krunal says

          Just write @csrf inside Form tag and you are good to go.

  15. Aondongu says

    This is a cool and informative application. However, I’m getting this issue when I try to load the index view:
    Undefined variable: passports (View: C:\xampp\htdocs\passport\resources\views\index.blade.php)

    Is anyone else having this issue?

    1. Siva says

      That means ,your controller is not able to pass the variable to view.
      Checkout this index function:
      $passports=\App\Passport::all();
      return view(‘index’,compact(‘passports’));

      and the foreach loop:
      @foreach($passports as $passport)

      1. aondongu tivzenda says

        thank you

  16. aom says

    Hello, thanks for this tutorial.
    But in step 6 I got the error: “Undefined variable: name”
    And this line is marked: “$passport->filename=$name;”
    What could I did wrong?

    1. Krunal says

      You need to define the $name before your statement. If your request contain that variable then write $request->get(‘name’);

      1. aom says

        Thank you 🙂

  17. Luckie says

    When i create a data i get this in the index page

    The page has expired due to inactivity.

    Please refresh and try again.

    1. Krunal says

      I guess, CSRF token will be the issue. In this form tag just write @csrf and it will resolve it.

  18. mohamed says

    i want to use back-end for this what i should do ? also add user registration and login
    i’m new to laravel

    1. Mitrajyoti says

      Yes, this is my question too. I had been a CI developer where I used a different CI module for back end coding.

  19. Chameer says

    Thanks…Good work

  20. Mitrajyoti says

    Hello Krunal, thanks for for this nice and brief tutorial. You are also a good teacher here. Can you tell me what should I do for my tables having different type of relations (one to many / many to one / many to many) and need to use joining among them ? Thanks in advance.

  21. Sam says

    Realy its very useful tutorial…..
    Can you please add LIVE DEMO, its will useful for new users like me.
    Hope you will do…
    Thank you Mr.Krunal

  22. Ismael says

    Hi. Tks for this tutorial.

    It’s very useful.

  23. Alex says

    Hi. Thanks for this tutorial.

    You can use:
    php artisan make:controller PassportController –resource –model=Passport

    In this case, you can use $passport without using $request:
    //PassportController.php

    /**
    * Show the form for editing the specified resource.
    *
    * @param AppPassport $passport
    * @return IlluminateHttpResponse
    */
    public function edit(Passport $passport)
    {
    return view(‘edit’,compact(‘passport’));
    }

    And in blade:
    Edit

    https://laravel.com/docs/5.6/controllers#resource-controllers

  24. sharad says

    i got the error when i submit details after insertion,error is The page has expired due to inactivity.

    Please refresh and try again.,why i am getting this ,all code is right

  25. sharad says

    i got the error in this that is The page has expired due to inactivity.

    Please refresh and try again. and values are not insert into database table

    1. Anto says

      The page has a CSRF TOKEN .. Replace it with
      {{ csrf_field() }}

      This will remove the error

  26. Benjamin Chukwudi says

    hello, thanks for this wonderful tutorial,

    pls how can i control the input forms to view, this may be off topic, bt i need to implement this feature, am building a form with many input like 18, and i want to be able to control the number of fields to show, by just ticking the ones to show, then, when i open the form create page i will see only the selected fields to display

  27. Sugaraa says

    Thanks man

Leave A Reply

Your email address will not be published.

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