Complete Laravel 8 CRUD Application Tutorial

Share this Article

Laravel 8 is an open source PHP Framework. Inside this article we will see about implementation of Laravel 4 CRUD Application Tutorial. Nowadays, every application have a common operation CRUD. CRUD stands for Create, Read, Update & Delete.

We will see, about each operation of CRUD in Laravel 8 in a very clear way. We will interact with application database, model etc.

Let’s get started CRUD Example in Laravel 8.


Installation of Laravel 8 Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Click here to Install Composer ? Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel 8 application into system. To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel 8 already installed at system.


Application Database Configuration

Inside this we will make database configuration using .env file. So to connect with database we need to pass database name, username, password etc.

Let’s open .env file and provide the following details.

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

By the above step we are now successfully connected with database. Now, we can start with Laravel 8 CRUD application tutorial.


Create Application Migration

As we are going to create CRUD (Create, Read, Update, Delete) application in laravel. So let’s take an example as product.

Here we have to create a migration which creates a products table using Laravel 8 php artisan command.

$ php artisan make:migration create_products_table --create=products

After running this command at your terminal, you will see one file will be created at this following path database/migrations.

Here is the modified code for migration file, so just copy and paste into your migration file for table scheme products.

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('amount');
            $table->text('description');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Now, you have to run this given command to migrate the above file.

$ php artisan migrate

Above command will creates a products table in database.


Add Application Controller and Model

Next, we should create a new controller as ProductController. We are going to create a resource controller by running the given command.

$ php artisan make:controller ProductController --resource --model=Product

This command will creates a ProductController i.e a resource controller and a model. You can find the created files at this path app/Http/Controllers/ProductController.php & model at app/Models/Product.php

In this resource controller we will have these following methods:

  • index()
  • create()
  • store()
  • show()
  • edit()
  • update()
  • delete()

Open up the model from this path app/Models/Product.php and write this updated code.

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Product extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'description', 'amount'
    ];
}

Open up app/Http/Controllers/ProductController.php and paste this updated code.

<?php
  
namespace App\Http\Controllers;
   
use App\Models\Product;
use Illuminate\Http\Request;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::latest()->paginate(5);
    
        return view('products.index',compact('products'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }
     
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('products.create');
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'amount' => 'required',
        ]);
    
        Product::create($request->all());
     
        return redirect()->route('products.index')
                        ->with('success','Product created successfully.');
    }
     
    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return view('products.show',compact('product'));
    } 
     
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view('products.edit',compact('product'));
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'amount' => 'required',
        ]);
    
        $product->update($request->all());
    
        return redirect()->route('products.index')
                        ->with('success','Product updated successfully');
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();
    
        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }
}

Application Resource Route Settings

Open up route configuration file web.php from path routes/web.php.

Add the following code into it.

use App\Http\Controllers\ProductController;
  
Route::resource('products', ProductController::class);

If we are interested to see the routes associated with Resource Controller, back to terminal and type command $ php artisan route:list


Adding Application Layout Files

Inside this we need to create layout files of product. Let’s create a new folder products at path resources/views/ then create blade files of CRUD application into it.

So we have to create the following bellow blade files:

  • layout.blade.php
  • index.blade.php
  • create.blade.php
  • edit.blade.php
  • show.blade.php

Open up the file resources/views/products/layout.blade.php and paste the following given code into it.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 CRUD Application Tutorial - Online Web Tutor</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
  
<div class="container" style="margin-top:100px;">
    @yield('content')
</div>
   
</body>
</html>

Open file resources/views/products/index.blade.php

@extends('products.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h3>Laravel 8 CRUD Application Tutorial - Online Web Tutor</h3>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('products.create') }}"> Add New Product</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
   
    <table class="table table-bordered" style="margin-top:20px;">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Amount</th>
            <th>Description</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->amount }}</td>
            <td>{{ $product->description }}</td>
            <td>
                <form action="{{ route('products.destroy',$product->id) }}" method="POST">
   
                    <a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>
    
                    <a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>
   
                    @csrf
                    @method('DELETE')
      
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
  
    {!! $products->links() !!}
      
@endsection

Open up the file resources/views/products/create.blade.php

@extends('products.layout')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Product</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There are some issues.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('products.store') }}" method="POST">
    @csrf
  
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                <input type="text" name="name" class="form-control" placeholder="Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Amount:</strong>
                <input type="number" name="amount" class="form-control" placeholder="Amount">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Description:</strong>
                <textarea class="form-control" style="height:150px" name="description" placeholder="Description"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
   
</form>
@endsection

Open up the file resources/views/products/edit.blade.php

@extends('products.layout')

@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Edit Product</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
        </div>
    </div>
</div>

@if ($errors->any())
<div class="alert alert-danger">
    <strong>Whoops!</strong> There are some issues.<br><br>
    <ul>
        @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

<form action="{{ route('products.update',$product->id) }}" method="POST">
    @csrf
    @method('PUT')

    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                <input type="text" name="name" value="{{ $product->name }}" class="form-control" placeholder="Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Amount:</strong>
                <input type="number" name="amount" value="{{ $product->amount }}" class="form-control" placeholder="Amount">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Detail:</strong>
                <textarea class="form-control" style="height:150px" name="description"
                    placeholder="Detail">{{ $product->description }}</textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>

</form>
@endsection

Open up the file resources/views/products/show.blade.php

@extends('products.layout')
  
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Product</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $product->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Amount:</strong>
                {{ $product->amount }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Description:</strong>
                {{ $product->description }}
            </div>
        </div>
    </div>
@endsection

Finally, we are ready to run Laravel 8 CRUD application.


Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

Open up the URL: http://127.0.0.1:8000/products

When we click on Add New Product button it will open http://127.0.0.1:8000/products/create

When we add products from Create Form, we will see products list at /products URL. In the list we will see the Edit & Delete button.

We hope this article helped you to learn about Laravel 8 CRUD Application Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

13 thoughts on “Complete Laravel 8 CRUD Application Tutorial”

  1. Fantastic goods from you, man. I have take into account your stuff
    prior to and you are just extremely great.
    I really like what you’ve obtained right here, certainly like what you are stating and the way through which you are saying it.

    You’re making it entertaining and you continue to care for to stay it smart.
    I cant wait to learn far more from you. This is really a great site.

    Reply
  2. Howdy! Would you mind if I share your blog with my twitter group?
    There’s a lot of folks that I think would really appreciate your content.
    Please let me know. Thank you

    Reply

Leave a Comment