Laravel 5.6 CRUD Tutorial with Example

Here are the steps to create a crud application in Laravel 5.6:

Step 1: Configure Laravel 5.6 Project.

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

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

Step 2: Set up a MySQL database in .env file.

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.

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.

  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();
        });
    }

Migrate the table by the following command.

php artisan migrate

In the database, you can see the passports table.

Step 4: Build a view file to add the information to 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 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');

Turn to your terminal and type the next command.

php artisan route:list

The next step would be to go to the PassportController.php file and add some code to create() function.

// 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 the 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 index.blade.php. So, in the 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 an individual blade file called index.blade.php file and place 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>

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 the 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>

The 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, this task is for you to complete. I was hoping you could complete this update module 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');
    }

That’s it!

64 thoughts on “Laravel 5.6 CRUD Tutorial with Example”

  1. 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.

    Reply
  2. 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

    Reply
  3. 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

    Reply
  4. 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

    Reply
  5. 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.

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

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

    php artisan make:controller PassportController –resource

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

    Reply
  9. 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

    Reply
  10. 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 ?

    Reply
    • 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.

      Reply
  11. 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?

    Reply
  12. 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?

    Reply
  13. When i create a data i get this in the index page

    The page has expired due to inactivity.

    Please refresh and try again.

    Reply
  14. 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.

    Reply
  15. 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

    Reply
  16. 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

    Reply
  17. 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

    Reply
  18. 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

    Reply
  19. 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

    Reply
  20. Hi, Thanks for the blog it was really useful i am stuck with edit functionality getting error variable passport not declare. Can you share the possible solution, Thanks in Advance

    Reply
  21. Thank you.
    Two points please.
    1. Make a downloadable for newbies.
    2. In the downloadable include the last two views for update and destroy.

    Fully appreciate.

    Reply
  22. when i am submitting form i am getting screen loads of errors even i have mentioned model also in above.

    errors like these

    in VerifyCsrfToken.php line 68
    at VerifyCsrfToken->handle(object(Request), object(Closure))
    in Pipeline.php line 148
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    in Pipeline.php line 53
    at Pipeline->Illuminate\Routing\{closure}(object(Request))
    in ShareErrorsFromSession.php line 49
    at ShareErrorsFromSession->handle(object(Request), object(Closure))
    in Pipeline.php line 148
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    in Pipeline.php line 53
    at Pipeline->Illuminate\Routing\{closure}(object(Request))
    in StartSession.php line 64
    at StartSession->handle(object(Request), object(Closure))
    in Pipeline.php line 148

    Reply
  23. require(/opt/lampp/htdocs/mine/passportappointmentsystem/vendor/autoload.php): failed to open stream: No such file or directory in /opt/lampp/htdocs/mine/passportappointmentsystem/artisan on line 18

    Reply
  24. Good night, I’m running the following code
    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’);
    }
    is returning invalid variable

    what would be the solution?

    Reply

Leave a Comment

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