AppDividend
Latest Code Tutorials

Laravel 5.8 CRUD Tutorial With Example For Beginners

13

Laravel 5.8 CRUD Tutorial With Example For Beginners is today’s topic. You can upgrade your Laravel’s 5.8 version by going to this link. Laravel 5.8 continues the improvements made in Laravel 5.7 by introducing the following features.

  1. has-one-through Eloquent relationships.
  2. Improved email validation.
  3. convention-based automatic registration of authorization policies.
  4. DynamoDB cache and session drivers.
  5. Improved scheduler timezone configuration.
  6. Support for assigning multiple authentication guards to broadcast channels.
  7. PSR-16 cache driver compliance, improvements to the artisan serve command.
  8. PHPUnit 8.0 support.
  9. Carbon 2.0 support.
  10. Pheanstalk 4.0 support, and a variety of other bug fixes and usability improvements.

You can find the detailed guide on Laravel 5.8 releases.

#Server Requirements For Laravel 5.8

The following are the server requirements.

  1. PHP >= 7.1.3
  2. OpenSSL PHP Extension
  3. PDO PHP Extension
  4. Mbstring PHP Extension
  5. Tokenizer PHP Extension
  6. XML PHP Extension
  7. Ctype PHP Extension
  8. JSON PHP Extension
  9. BCMath PHP Extension

#Prerequisites

For this project, I am using Visual Studio Code. If you do not know how to configure PHP on VSCode then I have also written the tutorial on this blog regarding how to configure Visual Studio Code For PHP Developers.

First, you need to check the PHP version. Type the following command.

php -v

My PHP version is 7.2.14.

Prerequisites of Laravel 5.8 CRUD

If your version is less than above PHP version, then I would suggest you upgrade your PHP version.

If you are on a Mac, then you can update your PHP version using homebrew.

First, remove the old versions of PHP and then install it using the following command.

brew install httpd php72
brew install php72 --with-httpd --with-thread-safety

For more information, check out this great guide.

Next thing is we need a Composer. The composer is a PHP Dependency Manager. We can pull the different packages using the composer.

Install the composer using the following command.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Next step is to move the composer to the global directory.

mv composer.phar /usr/local/bin/composer

Now, your composer has been installed successfully.

#For Linux Ubuntu Guide

On Ubuntu, you can follow these instructions to install the latest PHP version as well as Composer.

First, add the ondrej/php PPA which contains the latest version of PHP.

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

Next, install PHP 7.2 using the following command.

sudo apt-get install php7.2

Now, you need to install the required modules of PHP 7.2.

And Finally, install the Composer. Go to the home directory, and we will install composer using cURL.

curl -sS https://getcomposer.org/installer -o composer-setup.php

You can then install composer globally on your system by using the following command.

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

Now, type the following command in your terminal.

composer

It will display something like below.

Laravel 5.8 CRUD Tutorial

Laravel 5.8 CRUD Tutorial With Example

I have already written Laravel 5.6 CRUD, Laravel 5.7 CRUD on this blog.

You can install Laravel 5.8 via global installer or using the Composer Create-Project command.

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

 

Laravel 5.8 CRUD Tutorial With Example For Beginners

Now, go inside the project and open the project in your favorite editor.

cd laravel58crud
code .

#Step 1: Configure the 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.

I have created a MySQL database called laravel58crud and now write the MySQL credentials inside the .env file. Before creating migrations, We will need to set up our database, assuming you know how to create a database using phpmyadmin. After creating the database, we will add the database credentials in our application. Laravel has a .env environment file which will have all the sensitive data like database details, mail driver details, etc. because it’s not recommended to store such information directly inside the code (environment files are not limited to PHP. They are used in all other significant frameworks). Values inside the .env files are loaded inside the files from the config directory. .env file is located at the root of our application.

Whenever you make changes to .env file then don’t forget to restart the server ( if you are using laravel dev server) and if you are using a virtual host and changes don’t seem to take effect then just run php artisan config:clear (This command will clear the configuration cache) in your terminal.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel58crud
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

 

Configure the MySQL Database

We will create a CRUD operation on Books. So the user can create, read, update, and delete the books from the database. So, let’s create a model and migration files.

#Step 2: Create a model and migration files.

Since we have set up our database, now let’s take a look at database migrations. Migration is used to store the details about a database table, and it’s properties, so you don’t have to manually create all the tables by going to the database interface or something like phpmyadmin. We can develop migrations using artisan with “make: migration” command.

Type the following command to create a model and migration files.

php artisan make:model Book -m

In laravel, the name of the model has to be singular, and the name of the migration should be plural so it can automatically find the table name. You can find these migration files in database/migrations directory. Laravel by default comes with two migrations namely users and password_resets (all migration files are prepended with a timestamp), which are used for authentication. If you want to create a migration but have a different table name in mind then you can explicitly define the table name with “ — create” flag:

It will create a Book.php file and [timestamp]create_books_table.php migration file.

Now, open the migration file inside the database >> migrations >> [timestamp]create_books_table file and add the following schema inside it.

public function up()
{
     Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('book_name');
        $table->string('isbn_no');
        $table->integer('book_price');
        $table->timestamps();
     });
}

When you open the create_books_table.php, you will see two methods, up() and down(). up() is used for creating/updating tables, columns, and indexes. The down() method is used for reversing the operation done by up() method.

Inside up() method, We have Schema: create(‘table_name’, callback) method which will be used for creating a new table. Inside the callback, we have $table->bigIncrements(‘id’) which will create an auto_increment integer column with a primary key and argument ‘id’ is the name of the column. Second one is $table->timestamps() which will create two timestamp columns created_at and updated_at. created_at will be filled when a row is created and updated_at when a row is updated. We will add two columns title and body (for the sake of simplicity) but if you want to know the types of the available columns then see the list.

Now, create a table in the database using the following command.

php artisan migrate

 

Laravel 5.8 CRUD Tutorial With Example For Beginner

Above command will run the migrations and create all the tables. It will execute the up() method. If you want to reverse the migrations, you can use migrate: rollback command which will execute down() method like php artisan migrate: rollback.

So, in the database, the table is created successfully.

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

// Book.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = ['book_name', 'isbn_no', 'book_price'];
}

We can specify properties to modify the behavior of a model. We can write the $table property which is used to determine the name of the table that this model will interact with. By default, It will define the table name as the plural of the model name, e.g., books table for Book model and users table for User model. When you don’t want to use timestamps on your table, then you will also have to specify $timestamps property and set it to false in your Model because Laravel expects your table to have created_at and updated_at timestamp columns.

#Step 3: Create routes and controller

First, create the BookController using the following command.

php artisan make:controller BookController --resource

Note that we have also added a — resource flag which will define six methods inside the BookController namely:

  1. Index (used for displaying a list of Books)
  2. Create (will show a view with a form for creating a Book)
  3. Store (used for creating a Book inside the database. Note: create method submits to store method)
  4. Show (will display a specified Book)
  5. Edit (will show a form for editing a Book. Form will be filled with the existing Book data)
  6. Update (Used for updating a Book inside the database. Note: edit submits to update method)
  7. Destroy (used for deleting a specified Book)

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

<?php

// BookController.php

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

Route::resource('books', 'BookController');

We can pass dynamic parameters with {} brackets, and you might have noticed that show, update, and destroy has the same url but different methods, so it’s legit. Just like — resource flag, laravel has a method called resource() that will generate all the above routes. You can also use that method instead of specifying them individually like above.

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.8 CRUD Tutorial

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

<?php

// BookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

#Step 4: Create the views

Inside resources >> views folder, create the following three files.

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

Also inside the 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.

<!-- layout.blade.php -->

<!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.8 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 4 by adding the app.css.

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

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

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Book
  </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('books.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Book Name:</label>
              <input type="text" class="form-control" name="book_name"/>
          </div>
          <div class="form-group">
              <label for="price">Book ISBN Number :</label>
              <input type="text" class="form-control" name="isbn_no"/>
          </div>
          <div class="form-group">
              <label for="quantity">Book Price :</label>
              <input type="text" class="form-control" name="book_price"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Book</button>
      </form>
  </div>
</div>
@endsection

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

// BookController.php

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

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

php artisan serve

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

You can see something like this.

Create the views

#Step 5: Add Validation rules and save data

In this step, we will add the Laravel Validation.

Now, the first step inside the BookController.php is that import the namespace of Book model inside the BookController.php file.

// BookController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;

Now, write the following code inside the BookController.php file’s store() function.

// BookController.php

public function store(Request $request)
{
    $validatedData = $request->validate([
         'book_name' => 'required|max:255',
         'isbn_no' => 'required|alpha_num',
         'book_price' => 'required|numeric',
     ]);
     $book = Book::create($validatedData);

     return redirect('/books')->with('success', 'Book is successfully saved');
}

Here, what we have done is first check for all three fields of the form.

If any of the rules are failed by the incoming data, then it will directly go to the form with the error messages.

Store method has $request object as a parameter which will be used to access form data. The first thing you want to do is validate the form data. We can use the $request->validate() method for validation, which will receive an array of validation rules.

Validation rules is an associative array. Key will be the field_name and value with being the validation rules. The second parameter is an optional array for custom validation messages. Rules are separated with pipe sign “|.” We are using the most basic validation rules. First is “required” which means the field_name should not be empty (“nullable” rule is vice versa), “string” means it should be a string value, “min” is the limit of minimum characters for a string in an input field and “max” is the maximum characters. “unique:table,column” with see if the same value does not exists in the database (comes handy for storing emails or any other unique data).

If validation fails, then it will redirect us back. After validation, we are creating a new book and save that book in the database.

We need to loop through that error messages inside the create.blade.php file which we have already done it.

If you leave all the form fields empty, then you will find an error message like this image.

Laravel 5.8 validation example

Now, if you fill the form fields correctly, then it will create a new row in the database. I have created a new book.

Laravel Create Example

Some Methods for accessing form data:

$request->input('field_name'); // access an input field
$request->has('field_name'); // check if field exists
$request->title; // dynamically access input fields
request('key') // you can use this global helper if needed inside a view

Helpful redirecting methods:

return redirect('/books'); // to a specific url
return redirect(url('/books')); // to a specific url with url helper
return redirect(url()->previous()); // to a previous url
return redirect()->back(); // redirect back (same as above)

#Step 6: Display the data.

Now, we need to write the BookController’s index function to return the index view with the data fetched from the database. Write the following code inside the index() function.

// BookController.php

public function index()
{
     $books = Book::all();

     return view('index', compact('books'));
}

Okay, now create the file called index.blade.php inside the views folder and add the following code.

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

@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>Book Name</td>
          <td>ISBN Number</td>
          <td>Book Price</td>
          <td colspan="2">Action</td>
        </tr>
    </thead>
    <tbody>
        @foreach($books as $book)
        <tr>
            <td>{{$book->id}}</td>
            <td>{{$book->book_name}}</td>
            <td>{{$book->isbn_no}}</td>
            <td>{{$book->book_price}}</td>
            <td><a href="{{ route('books.edit',$book->id)}}" class="btn btn-primary">Edit</a></td>
            <td>
                <form action="{{ route('books.destroy', $book->id)}}" method="post">
                  @csrf
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </tbody>
  </table>
<div>
@endsection

Here, we have looped through the books array and display the data in the tabular format.

Also, we have added two buttons for edit and delete operation.

#Step 7: Create Edit and Update Operation

First, we need to add the following code inside the BookController.php file’s edit function.

// BookController.php

public function edit($id)
{
    $book = Book::findOrFail($id);

    return view('edit', compact('book'));
}

Now, create a new file inside the views folder called edit.blade.php and add the following code.

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

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Edit Book
  </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('books.update', $book->id) }}">
          <div class="form-group">
              @csrf
              @method('PATCH')
              <label for="name">Book Name:</label>
              <input type="text" class="form-control" name="book_name" value="{{$book->book_name}}"/>
          </div>
          <div class="form-group">
              <label for="price">Book ISBN Number :</label>
              <input type="text" class="form-control" name="isbn_no" value="{{$book->isbn_no}}"/>
          </div>
          <div class="form-group">
              <label for="quantity">Book Price :</label>
              <input type="text" class="form-control" name="book_price" value="{{$book->book_price}}"/>
          </div>
          <button type="submit" class="btn btn-primary">Update Book</button>
      </form>
  </div>
</div>
@endsection

In this file, you can show the values of the particular row using its unique id inside the form fields.

So, when you hit this URL: http://localhost:8000/books/1/edit, you will see something like below image.

 

Edit Functionality in Laravel

Now, add the following code inside the BookController’s update() function.

// BookController.php

public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'book_name' => 'required|max:255',
            'isbn_no' => 'required|alpha_num',
            'book_price' => 'required|numeric',
        ]);
        Book::whereId($id)->update($validatedData);

        return redirect('/books')->with('success', 'Book is successfully updated');
    }

So now, you can edit and update the data into the database successfully.

#Step 8: Create Delete Functionality

Write the following code inside the BookController’s destroy function.

// BookController.php

public function destroy($id)
    {
        $book = Book::findOrFail($id);
        $book->delete();

        return redirect('/books')->with('success', 'Book is successfully deleted');
    }

Now, go to this URL: http://localhost:8000/books and try to delete the book.

You can see that you have successfully deleted the book.

So, our complete BookController.php code looks like below.

<?php

// BookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;

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

        return view('index', compact('books'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'book_name' => 'required|max:255',
            'isbn_no' => 'required|alpha_num',
            'book_price' => 'required|numeric',
        ]);
        $book = Book::create($validatedData);

        return redirect('/books')->with('success', 'Book is successfully saved');
    }

    /**
     * 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)
    {
        $book = Book::findOrFail($id);

        return view('edit', compact('book'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'book_name' => 'required|max:255',
            'isbn_no' => 'required|alpha_num',
            'book_price' => 'required|numeric',
        ]);
        Book::whereId($id)->update($validatedData);

        return redirect('/books')->with('success', 'Book is successfully updated');
    }

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

        return redirect('/books')->with('success', 'Book is successfully deleted');
    }
}

So, we have completed a Laravel 5.8 CRUD operations tutorial with the example from scratch.

If you are interested in the FrontEnd framework like Vue.js then check out my Vue Laravel CRUD example and Angular Laravel Tutorial Example.

I have put this code on Github so you can check it out as well.

GITHUB CODE

13 Comments
  1. Rohi Arora says

    Thanks for the clear and concise tutorial.

  2. yasser says

    thanks ….
    it helped me a lot

  3. Edson says

    Clear and concise. Thank you.

  4. LaravelCode says

    Hello

  5. Jeff says

    Thank you so much, have really learned a lot

  6. Murray Crane says

    Krunal,

    Great tutorial, not too complex, does exactly what it says. Has been a go-to reference work while developing an intranet for my employer.

    Just to let you know, there are a couple of typos in the edit.blade.php code in step 7, the labels for isbn_no and book_price are for ‘price’ and ‘quantity’ respectively (rather than ‘isbn_no’ and ‘book_price’).

  7. James Smith says

    Nice tutorial especially for those who are beginners. Thanks for sharing this informative article of Laravel programming. Lots of things are to be learned about in this. Keep up the good work.

  8. King Josaphat Chewa says

    Awesome. Thank you for this tutorial. I’ve learned a lot and I just bookmarked this page. Coming from Node.js, it was not really difficult to follow along. I realize that things are so similar.

  9. geetika kalra says

    Very good tutorial for begineers.

  10. Waqar says

    Method validate does not exist.

  11. Raijin says

    Thanks for the tutorial! 😀
    I hope you can create tutorial about creating API using laravel
    please send me at raijin.ec@gmail.com

  12. Ashish Gupta says

    Hi,
    I am looking a tutorial on Laravel which provide interface to both web and mobile along with authentication.

    Thanks

  13. ethean says

    thank you guys

Leave A Reply

Your email address will not be published.

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