In this tutorial, we will learn how to perform Laravel 9 CRUD operations with an example. We will implement the Create, Show, Update, and Delete operations from scratch.
We will use the product example to create products, show products, update products, and delete products. Let’s see how to perform Laravel 9 CRUD operations with an example.
Step 1: Install Laravel 9
If you already have installed Laravel 9 on your local machine then you can skip this step. You can easily install the fresh version of Laravel 9 by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app
.
composer create-project --prefer-dist laravel/laravel demo-app
or use the following command to install the specific Laravel version
composer create-project laravel/laravel:^9.0 demo_app
Notes: To install Laravel 9 you need PHP 8.0. So make sure you have installed PHP 8.0 in your local WAMP, LAMP, MAMP, etc.
Step 2: Database Configuration
In this step, we will add the database credentials to the .env
file. We need to add the database Name, database Host, MySQL username, and password. So let’s open the .env file and add all the details below as per your setup.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=add-your-database-name(demo-app)
DB_USERNAME=add-your-database-username(root)
DB_PASSWORD=add-your-database-password(may be blank)
Step 3: Create Migration
Now, we will create a products
table using the Laravel migrations. Let’s run the below command to create a migration.
cd demo-app
php artisan make:migration create_products_table --create=products
After running the above command a new migration file will be created in “database/migrations” directory.
database/migrations/2022_05_29_20000_create_products_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('price');
$table->longText('description')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('products');
}
}
Now, run the below command to create database tables.
php artisan migrate
Step 4: Create A Model
In this step, we will create a Product model which helps us to connect with the products
table so that we can perform the database operations using the model. Run the below command to create a model.
php artisan make:model Product
Then the new file will be created in demo-app/app/Models/Product.php
. In the model add the name, price, and description fields in the fillable array.
app/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'price', 'description'
];
}
Step 5: Create ProductController
Let’s create a ProductController
with resource option. The resource option will add all the default methods to the controller. To create a controller run the below command:
php artisan make:controller ProductController --resource
After running the above command a new file will be created in the Controllers
directory. Let’s open it and add the following code:
app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
$products = Product::latest()->paginate(10);
return view('products.index', compact('products'))
->with('i', (request()->input('page', 1) - 1) * 10);
}
public function create()
{
return view('products.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'description' => 'required',
]);
Product::create($request->all());
return redirect()
->route('products.index')
->with('success', 'Product has successfully created.');
}
public function show(Product $product)
{
return view('products.show', compact('product'));
}
public function edit(Product $product)
{
return view('products.edit', compact('product'));
}
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'description' => 'required',
]);
$product->update($request->all());
return redirect()
->route('products.index')
->with('success', 'Product has successfully updated.');
}
public function destroy(Product $product)
{
$product->delete();
return redirect()
->route('products.index')
->with('success', 'Product has successfully deleted.');
}
}
Step 6: Create Resource Routes
We need to add resource routes in routes/web.php
file to perform the Laravel CRUD operation.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
Route::resource('products', ProductController::class);
This single route declaration creates multiple routes to handle a variety of actions as defined in below table:
Verb | URI | Action | Route Name |
---|---|---|---|
GET | /products | index | products.index |
GET | /products/create | create | products.create |
POST | /products | store | products.store |
GET | /products/{product} | show | products.show |
GET | /products/{product}/edit | edit | products.edit |
PUT/PATCH | /products/{product} | update | products.update |
DELETE | /products/{product} | destroy | products.destroy |
Step 7: Create Blade/HTML File
At last, we need to create different view blade files in the views
folder to perform Laravel crud operation for example.
We first need to create a layouts.blade.php
file that can be extended with other product view files so we don’t need to repeat HTML. Let’s create the following list of blade files.
- layout.blade.php
- index.blade.php
- create.blade.php
- edit.blade.php
- show.blade.php
resources/views/products/layout.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 CRUD Operations With Example - ScratchCode.IO</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
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">
<h2>Laravel 9 CRUD Operations with Example - ScratchCode.IO</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('products.create') }}">Create 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">
<thead>
<tr>
<th>Sr. No.</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody>
@foreach ($products as $product)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->detail }}</td>
<td>
<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>
<form action="{{ route('products.destroy',$product->id) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
{!! $products->links() !!}
@endsection
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 were some problems with your input.<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>Price:</strong>
<input type="text" name="price" class="form-control" placeholder="Price">
</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="detail" 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
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 were some problems with your input.<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>Price:</strong>
<input type="text" name="price" value="{{ $product->price }}" class="form-control" placeholder="Price">
</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">{{ $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">Save</button>
</div>
</div>
</form>
@endsection
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>Price:</strong>
{{ $product->price }}
</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
Step 8: Output – Laravel 9 CRUD Operation With Example
Hurray! We have completed all steps for the Laravel 9 CRUD operation with an example. Let’s run the below command and see how it’s working.
php artisan serve
After running the above command, open your browser and visit the site below URL:
http://localhost:8000/products
Additionally, read our guide:
- Laravel: Blade Switch Case Statement Example
- Laravel: Switch Case Statement In Controller Example
- Laravel: Change Column Type In Migration
- 2fa Laravel With SMS Tutorial With Example
- How To Use Where Date Between In Laravel
- How To Add Laravel Next Prev Pagination
- Laravel Remove Column From Table In Migration
- Laravel: Get Month Name From Date
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Update Pivot Table In Laravel
- How To Install Vue In Laravel 8 Step By Step
- How To Handle Failed Jobs In Laravel
- Best Ways To Define Global Variable In Laravel
- How To Get Latest Records In Laravel
- Laravel Paypal Integration Tutorial With Example
- How To Pass Laravel URL Parameter
- Laravel Run Specific Migration
- Laravel Notification Tutorial With Example
- How To Schedule Tasks In Laravel With Example
- Laravel Collection Push() And Put() With Example
That’s it from our end. We hope this article helped you learn the Laravel 9 CRUD operations with an example.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!