Loading image

Blogs / Programming

Laravel 11 CRUD operations

Laravel 11 CRUD operations

  • Hamza Amjad
  • 0 Comments
  • 134 View

This code contains a simple implementation of CRUD (Create, Read, Update, Delete) operations in a Laravel application. It provides a straightforward example of how to build a product management system with the following features:

web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::get('/', function () {
    return view('products.create');
});

Route::controller(ProductController::class)->group(function(){
    Route::get('/products', 'index')->name('products.index');
    Route::get('/products/create', 'create')->name('products.create');
    Route::post('/products', 'store')->name('products.store');
    Route::get('/products/{product}/edit', 'edit')->name('products.edit');
    Route::put('/products/{product}', 'update')->name('products.update');
    Route::delete('/products/{product}', 'destroy')->name('products.destroy');
});


ProductController.php

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;

class ProductController extends Controller
{
    public function index() {
        $products = Product::orderBy('created_at', 'DESC')->get();
        return view('products.list', [
            'products' => $products
        ]);
    }

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

    public function store(Request $request) {
        $rules = [
            'name' => 'required|min:5|max:255',
            'sku' => 'required|min:3',
            'price' => 'required|numeric',
        ];

        if ($request->hasFile('image')) {
            $rules['image'] = 'image';
        }

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return redirect()->route('products.create')->withInput()->withErrors($validator);
        }

        $product = new Product();
        $product->name = $request->name;
        $product->sku = $request->sku;
        $product->price = $request->price;
        $product->description = $request->description;
        $product->save();

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('uploads/products'), $imageName);

            $product->image = $imageName;
            $product->save();
        }

        return redirect()->route('products.index')->with('success', 'Product created successfully');
    }

    public function edit($id) {
        $product = Product::findOrFail($id);
        return view('products.edits', [
            'product' => $product
        ]);
    }

    public function update($id, Request $request) {
        $product = Product::findOrFail($id);

        $rules = [
            'name' => 'required|min:5|max:255',
            'sku' => 'required|min:3',
            'price' => 'required|numeric',
        ];

        if ($request->hasFile('image')) {
            $rules['image'] = 'image';
        }

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return redirect()->route('products.edits', $product->id)->withInput()->withErrors($validator);
        }

        $product->name = $request->name;
        $product->sku = $request->sku;
        $product->price = $request->price;
        $product->description = $request->description;
        $product->save();

        if ($request->hasFile('image')) {
            // Delete old image if it exists
            if ($product->image) {
                File::delete(public_path('uploads/products/' . $product->image));
            }

            // Save the new image
            $image = $request->file('image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('uploads/products'), $imageName);

            $product->image = $imageName;
            $product->save();
        }

        return redirect()->route('products.index')->with('success', 'Product updated successfully');
    }

    public function destroy($id) {
        $product = Product::findOrFail($id);

        if ($product->image) {
            File::delete(public_path('uploads/products/' . $product->image));
        }

        $product->delete();
        return redirect()->route('products.index')->with('danger', 'Product deleted successfully');
    }
}



create.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>Create Product</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body style="background-color: #f8f9fa;">
    <div class="container mt-5">
        <!-- Title Section -->
        <div class="text-center mb-4">
            <h1 class="text-primary">CRUD</h1>
        </div>

        <!-- Back Button -->
        <div class="d-flex justify-content-end mb-4">
            <a href="{{ route('products.index') }}" class="btn btn-success">Back</a>
        </div>

        <!-- Main Form Card -->
        <div class="card shadow-lg">
            <div class="card-header">
                <h4 class="mb-0">Create Product</h4>
            </div>
            <div class="card-body">
                <form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf

                    <!-- Name Input -->
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" name="name" value="{{ old('name') }}" class="form-control form-control-lg @error('name') is-invalid @enderror" placeholder="Product Name">
                        @error('name')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- SKU Input -->
                    <div class="mb-3">
                        <label for="sku" class="form-label">SKU</label>
                        <input type="text" name="sku" value="{{ old('sku') }}" class="form-control form-control-lg @error('sku') is-invalid @enderror" placeholder="SKU">
                        @error('sku')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Price Input -->
                    <div class="mb-3">
                        <label for="price" class="form-label">Price</label>
                        <input type="number" name="price" value="{{ old('price') }}" class="form-control form-control-lg @error('price') is-invalid @enderror" placeholder="Price">
                        @error('price')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Description Input -->
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea name="description" class="form-control form-control-lg" rows="5" placeholder="Product Description">{{ old('description') }}</textarea>
                    </div>

                    <!-- Image Input -->
                    <div class="mb-3">
                        <label for="image" class="form-label">Product Image</label>
                        <input type="file" name="image" class="form-control form-control-lg">
                    </div>

                    <!-- Submit Button -->
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OoI7Nqa5IR2gmwnkXgFhO1U7DQ0V1rCkD5GF7DVi8KOGLVrrtYeaWeK1pybFqGM9" crossorigin="anonymous"></script>
</body>
</html>


list.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>Product CRUD</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <!-- Header Section -->
    <div class="bg-dark text-white text-center py-4">
        <h1>CRUD</h1>
    </div>

    <!-- Main Container -->
    <div class="container my-4">
        <!-- Create Button -->
        <div class="d-flex justify-content-end mb-3">
            <a href="{{ route('products.create') }}" class="btn btn-success">Create</a>
        </div>

        <!-- Product Details Card -->
        <div class="card">
            <div class="card-header">
                <h4>Product Details</h4>
            </div>
            <div class="card-body">
                <!-- Success Message -->
                @if (Session::has('success'))
                    <div class="alert alert-success">
                        {{ Session::get('success') }}
                    </div>
                @endif

                <!-- Product List Table -->
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Image</th>
                                <th>Name</th>
                                <th>SKU</th>
                                <th>Price</th>
                                <th>Created at</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if ($products->isNotEmpty())
                                @foreach ($products as $product)
                                    <tr>
                                        <td>{{ $product->id }}</td>
                                        <td>
                                            @if ($product->image)
                                                <img src="{{ asset('uploads/products/'.$product->image) }}" alt="Product Image" width="50" height="50">
                                            @else
                                                <span>N/A</span>
                                            @endif
                                        </td>
                                        <td>{{ $product->name }}</td>
                                        <td>{{ $product->sku }}</td>
                                        <td>RS {{ $product->price }}</td>
                                        <td>{{ \Carbon\Carbon::parse($product->created_at)->format('d/ m/ y') }}</td>
                                        <td>
                                            <a href="{{ route('products.edit', $product->id) }}" class="btn btn-sm btn-success">Edit</a>
                                            <button onclick="deleteProduct({{ $product->id }});" class="btn btn-sm btn-danger">Delete</button>
                                            <form id="delete-product-form-{{ $product->id }}" action="{{ route('products.destroy', $product->id) }}" method="POST" style="display: none;">
                                                @csrf
                                                @method('DELETE')
                                            </form>
                                        </td>
                                    </tr>
                                @endforeach
                            @else
                                <tr>
                                    <td colspan="7" class="text-center">No Products Found</td>
                                </tr>
                            @endif
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript for Delete Confirmation -->
    <script>
        function deleteProduct(id) {
            if (confirm('Are you sure you want to delete this product?')) {
                document.getElementById('delete-product-form-' + id).submit();
            }
        }
    </script>
</body>
</html>


edits.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>Create Product</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body style="background-color: #f8f9fa;">
    <div class="container mt-5">
        <!-- Title Section -->
        <div class="text-center mb-4">
            <h1 class="text-primary">CRUD</h1>
        </div>

        <!-- Back Button -->
        <div class="d-flex justify-content-end mb-4">
            <a href="{{ route('products.index') }}" class="btn btn-success">Back</a>
        </div>

        <!-- Main Form Card -->
        <div class="card shadow-lg">
            <div class="card-header">
                <h4 class="mb-0">Edit Product</h4>
            </div>
            <div class="card-body">
                <form action="{{ route('products.update', $product->id) }}" method="POST" enctype="multipart/form-data">
                    @method('put')
                    @csrf

                    <!-- Name Input -->
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" name="name" value="{{ old('name', $product->name ) }}" class="form-control form-control-lg @error('name') is-invalid @enderror" placeholder="Product Name">
                        @error('name')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- SKU Input -->
                    <div class="mb-3">
                        <label for="sku" class="form-label">SKU</label>
                        <input type="text" name="sku" value="{{ old('sku', $product->sku) }}" class="form-control form-control-lg @error('sku') is-invalid @enderror" placeholder="SKU">
                        @error('sku')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Price Input -->
                    <div class="mb-3">
                        <label for="price" class="form-label">Price</label>
                        <input type="number" name="price" value="{{ old('price', $product->price) }}" class="form-control form-control-lg @error('price') is-invalid @enderror" placeholder="Price">
                        @error('price')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Description Input -->
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea name="description" class="form-control form-control-lg" rows="5" placeholder="Product Description">{{ old('description', $product->description) }}</textarea>
                    </div>

                    <!-- Image Input -->
                    <div class="mb-3 justify-content-center">
                        <label for="image" class="form-label">Product Image</label>
                        <input type="file" name="image" class="form-control form-control-lg">
                        @if ($product->image !== "")
                            <img class="w-50 my-3" src="{{ asset('uploads/products/'.$product->image)}}" alt="">
                        @endif
                    </div>

                    <!-- Submit Button -->
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OoI7Nqa5IR2gmwnkXgFhO1U7DQ0V1rCkD5GF7DVi8KOGLVrrtYeaWeK1pybFqGM9" crossorigin="anonymous"></script>
</body>
</html>

 

  • Programming
Hamza Amjad Author

Hamza Amjad

Experience: 1. Web Developer in `DHA360`.                                                                                       (current role/ present) 2. Full-Stack Web Developer in `Soltridge`                        .........

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

Laravel 10 Eloquent whereBetween() Query: A Powerful Filtering Query

Laravel 10 Eloquent whereBetween() Query: A Powerful Filtering Query

showkat ali
/

Read More
How to Use Summernote Editor in Laravel 10?

How to Use Summernote Editor in Laravel 10?

showkat ali
/
Programming

Read More
How to use Job Queues in Laravel 10 step-by-step tutorial

How to use Job Queues in Laravel 10 step-by-step tutorial

showkat ali
/
Programming

Read More
Most Top Paying Technologies in 2024

Most Top Paying Technologies in 2024

showkat ali
/
Programming

Read More
How to pitch in ChatGPT in Education

How to pitch in ChatGPT in Education

Nasir Hussain
/
English

Read More
[FIXED]  target class [role] does not exist in  laravel 11

[FIXED] target class [role] does not exist in laravel 11

showkat ali
/
Programming

Read More