Laravel 10 CRUD Example step by step

Spread the love

Hello Guys,

In this tutorial, we’ll walk you through a comprehensive Laravel 10 Crud operation example. You can dive into the world of Laravel 10 Crud applications by following the steps outlined here. Whether you’re a beginner or looking to enhance your Laravel 10 Crud skills, this tutorial is a perfect starting point. Let’s embark on this journey together.

CRUD, an acronym for Create, Read, Update, and Delete, encompasses the fundamental operations necessary for integrating persistent storage into your application.

In our demonstration, we will utilize Laravel 10 to create a robust product CRUD application. Before configuring routes, controllers, views, and models for the product module, we’ll begin by setting up a products database with name and detail columns using Laravel 10 migrations. Additionally, for an appealing design, we’ll leverage the power of Bootstrap 5. So, follow these steps below to master the art of Laravel 10 Crud development.

Step 1: Install Laravel 10 CRUD App

To initiate the tutorial, start by installing a brand-new Laravel 10 application. If you’ve already created the project, feel free to skip the next step.

Also Read: how to Create Custom Artisan Command in LARAVEL

composer create-project laravel/laravel example-app

Step 2: Database Configuration

In the second step of setting up the database, it’s crucial to include the database name, MySQL username, and password. To achieve this, let’s navigate to the .env file and input the required information in the following format:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)

Step 3: Create a Migration

In this tutorial, we will demonstrate how to create a “products” table using Laravel migration. To accomplish this, we will utilize the following command to generate a migration file.

Also Read: How to Use LARAVEL DB Raw Query?

php artisan make:migration create_products_table --create=products

Once you execute this command, you’ll find a file situated within the “database/migrations” directory. To create the products table, it’s essential to insert the provided code into your migration file.

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

To initiate this migration, execute the following command:

php artisan migrate

Step 4: Create Controller and Model

In this step, generate a fresh resource controller called “ProductController” by employing the command provided below. A resource controller will be established using the following controller command.

Also Read: How To Create Repeater Field Using Bootstrap

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

After executing the command below, you will discover a new file located at “app/Http/Controllers/ProductController.php“.

Within this controller, seven default methods will be generated as follows:

1) index()

2) create()

3) store()

4) show()

5) edit()

6) update()

7) destroy()

Now, let’s copy the following code and place it within the ProductController.php file.

<?php
  
namespace App\Http\Controllers;
  
use App\Models\Product;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $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.
     */
    public function create(): View
    {
        return view('products.create');
    }
  
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
        
        Product::create($request->all());
         
        return redirect()->route('products.index')
                        ->with('success','Product created successfully.');
    }
  
    /**
     * Display the specified resource.
     */
    public function show(Product $product): View
    {
        return view('products.show',compact('product'));
    }
  
    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Product $product): View
    {
        return view('products.edit',compact('product'));
    }
  
    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Product $product): RedirectResponse
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
        
        $product->update($request->all());
        
        return redirect()->route('products.index')
                        ->with('success','Product updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Product $product): RedirectResponse
    {
        $product->delete();
         
        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }
}

Step 5: Add Resource Route

Next, it’s essential to create a resource route for your product CRUD application. To do this, simply include the following route in your “routes/web.php” file.

Also Read: How To Send Email In Laravel 9

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ProductController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group that
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::resource('products', ProductController::class);

Step 6: Add Blade Files

In the final stage of development, the focus is on creating blade files. To effectively develop a CRUD (Create, Read, Update, Delete) application, the process begins with the creation of a layout file, followed by the establishment of a new folder named ‘products,’ and ultimately, the creation of blade files. To construct the desired blade file, follow these steps:

1) layout.blade.php

2) index.blade.php

3) create.blade.php

4) edit.blade.php

5) show.blade.php

Now, let’s proceed by creating the specified file and inserting the code provided below.

resources/views/products/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 CRUD Application - itcodestuff.com</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

Also Read: How to use laravel cookies – Get, Set, Delete with example

@extends('products.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 10 CRUD Example from scratch - itcodestuff.com</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">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Details</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->detail }}</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

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>Detail:</strong>
                <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></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>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $product->detail }}</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/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>Details:</strong>
                {{ $product->detail }}
            </div>
        </div>
    </div>
@endsection

Run Laravel App:

Once you’ve successfully completed all the essential steps, it’s time to initiate the Laravel application. Execute the following command and hit “Enter” to launch your Laravel application:

Also Read: How To Generate PDF Files using DomPDF In Laravel 9

php artisan serve

To access the app’s output, simply input the provided URL into your web browser.

http://localhost:8000/products

Embrace the elite realm of Laravel insights – your compass to the best Laravel blog awaits.

4 thoughts on “Laravel 10 CRUD Example step by step”

  1. I admire the way you’ve explored this topic. Your post is insightful and thoughtfully written.

    Reply

Leave a Comment