Laravel 10 CRUD Application Example Tutorial

By Ved Prakash N | Apr 19, 2023 | Laravel
Share :

https://www.fundaofwebit.com/post/laravel-10-crud-application-example-tutorial

Laravel 10 CRUD Application Example Tutorial

Hi Guys,

In this post, you will be learning laravel 10 crud operation example. Here you will learn to build a laravel 10 crud application. We will use laravel 10 crud application for beginners. It's a simple example of how to create a crud in laravel 10.

so guys, in this crud example, we will create a product crud application using laravel 10. we will create a products table as laravel migration, then create routes, controller, view, and model files for the product module. To design the UI (user interface), we will use bootstrap 5.

So guys, let get started to create a crud operation with laravel 10.


Step 1: Install Laravel 10

lets install laravel 10 application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app


Step 2: Database Configuration

open .env file and setup the database connection as shown below:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=database_password


Step 3: Create Migration 

create products table into mysql database using migration laravel artisan command as follows:

php artisan make:migration create_products_table --create=products

After this command you will find one file in the following path "database/migrations/create_products_table.php" and you have to put below code in your migration file for creating the products table as follows.

<?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->string('price');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};


Now, lets migrate this into our database with the following command:

php artisan migrate


Step 4: Create Model with following command:

php artisan make:model Product

after this command, you find this file "App/Models/Product.php" file, open and put the below code:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $table = 'products';

    protected $fillable = [
        'name',
        'price',
        'description'
    ];
}


Step 5: Create Controller named ProductController with following command:

php artisan make:controller ProductController --resource

once created, move to the ProductController.php file in path: app/Http/Controller/ProductController.php and paste the below code:

<?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'));
    }

    /**
     * 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|string|max:255',
            'price' => 'required|numeric',
            'description' => 'required|string|max:255',
        ]);

        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|string|max:255',
            'price' => 'required|numeric',
            'description' => 'required|string|max:255',
        ]);

        $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 in path routes/web.php file

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


Step 6: Create the blade files

Go to path : resources/views/ and inside that Create a folder named products and then create the files listed below init.

1. layouts.blade.php
2. index.blade.php
3. create.blade.php
4. edit.blade.php
5. show.blade.php

So let's start creating the files and paste the below code.

resources/views/products/layout.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Laravel 10 CRUD Application</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">

</head>
<body>

    <div class="container">
        @yield('content')
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>

</body>
</html>


resources/views/products/index.blade.php

@extends('products.layout')

@section('content')

    <div class="card">
        <div class="card-header">
            <h2>
                Laravel 10 CRUD Example from scratch
                <a class="btn btn-primary float-end" href="{{ route('products.create') }}"> Create New Product</a>
            </h2>
        </div>
        <div class="card-body">

            @if (session('success'))
            <div class="alert alert-success">{{ session('success') }}</div>
            @endif

            <table class="table table-bordered">
                <tr>
                    <th>No</th>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Description</th>
                    <th width="280px">Action</th>
                </tr>
                @foreach ($products as $product)
                <tr>
                    <td>{{ ++$i }}</td>
                    <td>{{ $product->name }}</td>
                    <td>{{ $product->price }}</td>
                    <td>{{ $product->description }}</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" class="d-inline">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
                @endforeach
            </table>

            {!! $products->links() !!}

        </div>
    </div>

@endsection


resources/views/products/create.blade.php

@extends('products.layout')

@section('content')

    <div class="card">
        <div class="card-header">
            <h2>
                Add Product
                <a class="btn btn-danger float-end" href="{{ route('products.index') }}"> Back</a>
            </h2>
        </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>
            @endif

            <form action="{{ route('products.store') }}" method="POST">
                @csrf

                 <div class="row">
                    <div class="col-md-12 col-12">
                        <div class="mb-3">
                            <label>Name</label>
                            <input type="text" name="name" class="form-control" placeholder="Name" />
                        </div>
                    </div>
                    <div class="col-md-12 col-12">
                        <div class="mb-3">
                            <label>Price</label>
                            <input type="number" name="price" class="form-control" placeholder="Price" />
                        </div>
                        <div class="mb-3">
                            <label>Description</label>
                            <textarea class="form-control" name="description" rows="3" placeholder="Enter Description"></textarea>
                        </div>
                    </div>
                    <div class="col-md-12 col-12 text-center">
                        <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                </div>

            </form>

        </div>
    </div>

@endsection


resources/views/products/edit.blade.php

@extends('products.layout')

@section('content')

    <div class="card">
        <div class="card-header">
            <h2>
                Edit Product
                <a class="btn btn-danger float-end" href="{{ route('products.index') }}"> Back</a>
            </h2>
        </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>
            @endif

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

                 <div class="row">
                    <div class="col-md-12 col-12">
                        <div class="mb-3">
                            <label>Name</label>
                            <input type="text" name="name" class="form-control" value="{{ $product->name }}" placeholder="Name" />
                        </div>
                    </div>
                    <div class="col-md-12 col-12">
                        <div class="mb-3">
                            <label>Price</label>
                            <input type="number" name="price" class="form-control" value="{{ $product->price }}" placeholder="Price" />
                        </div>
                        <div class="mb-3">
                            <label>Description</label>
                            <textarea class="form-control" name="description" rows="3" placeholder="Enter Description">{{ $product->description }}</textarea>
                        </div>
                    </div>
                    <div class="col-md-12 col-12 text-center">
                        <button type="submit" class="btn btn-primary">Update</button>
                    </div>
                </div>

            </form>

        </div>
    </div>

@endsection


resources/views/products/show.blade.php

@extends('products.layout')

@section('content')

    <div class="card">
        <div class="card-header">
            <h2>
                Show Product
                <a class="btn btn-danger float-end" href="{{ route('products.index') }}"> Back</a>
            </h2>
        </div>
        <div class="card-body">

            <div class="row">
                <div class="col-md-12 col-12">
                    <div class="mb-3">
                        <label>Name</label>
                        <p>{{ $product->name }}</p>
                    </div>
                </div>
                <div class="col-md-12 col-12">
                    <div class="mb-3">
                        <label>Price</label>
                        <p>{{ $product->price }}</p>
                    </div>
                    <div class="mb-3">
                        <label>Description</label>
                        <p>{{ $product->description }}</p>
                    </div>
                </div>
            </div>

        </div>
    </div>

@endsection


Step 7: Lets serve the application by following command:

php artisan serve


Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/products


I hope, it will help you.

https://www.fundaofwebit.com/post/laravel-10-crud-application-example-tutorial

Share this blog on social platforms