Laravel 9 CRUD Application Tutorial with Example

By Sumeet Shroff
Last Updated On : February 28, 2023
Laravel 9 CRUD Application Tutorial with Example

Laravel is one of the most popular PHP frameworks for web development, known for its simplicity and expressive syntax. In this tutorial, we will be building a basic CRUD (Create, Read, Update, Delete) application using Laravel 9. We will start by setting up the Laravel 9 environment, creating a database, and then building the CRUD application.

Setting up Laravel 9 Environment

To begin with, we need to install Laravel 9 on our system. We can do this using Composer, a PHP package manager. Open up a command prompt and run the following command:

composer create-project --prefer-dist laravel/laravel laravel-crud

This will create a new Laravel 9 project named "laravel-crud". We can navigate to this directory by running the following command:

cd laravel-crud

Creating a Database

Next, we need to create a database for our CRUD application. We can do this by using phpMyAdmin or any other database management tool. Once we have created the database, we need to update our Laravel 9 application's .env file with the database credentials:

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

Creating a Model and Migration

Now, we will create a model and migration for our CRUD application using the following command:

php artisan make:model Product -m

This will create a model named "Product" and a migration file for the "products" table in our database. We can update the migration file with the following code:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->float('price');
        $table->timestamps();
    });
}

The above code will create a "products" table with columns for "name", "description", "price", and "timestamps". We can run the migration using the following command:

php artisan migrate

Creating a Controller

Next, we will create a controller for our CRUD application using the following command:

php artisan make:controller ProductController --resource

This will create a controller named "ProductController" with resourceful methods for our CRUD operations. We can update the controller with the following code:

public function index()
    {
        $products = Product::latest()->paginate(5);
        return view('products.index', compact('products'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }
public function create()
    {
        return view('products.create');
    }
public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'price' => 'required'
        ]);
        Product::create($request->all());
        return redirect()->route('products.index')
            ->with('success', 'Product created successfully.');
    }
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',
            'description' => 'required',
            'price' => 'required'
        ]);
        $product->update($request->all());
        return redirect()->route('products.index')
            ->with('success', 'Product updated successfully');
    }
public function destroy(Product $product)
    {
        $product->delete();
        return redirect()->route('products.index')
            ->with('success', 'Product deleted successfully');
    }

In the above code, we have created resourceful methods for our CRUD operations. The index() method fetches all products from the database and displays them in a paginated view. The create() method displays a form to create a new product. The store() method validates the request data and saves the new product to the database. The show() method displays a single product. The edit() method displays a form to edit an existing product. The update() method updates the product in the database with the new data. The destroy() method deletes a product from the database.

Creating Views

Now, we need to create views for our CRUD application. We will create views for the index, create, edit, and show pages. We can create a folder named "products" in the "resources/views" directory and create the following views:

  • index.blade.php: This view displays a paginated list of all products.
  • create.blade.php: This view displays a form to create a new product.
  • edit.blade.php: This view displays a form to edit an existing product.
  • show.blade.php: This view displays a single product. The views can be created using the following code:

index.blade.php

@extends('products.layout')
@section('content')
    <div>
        <div>
            <div>
                <h2>Products CRUD</h2>
            </div>
            <div>
                <a href="{{ route('products.create') }}"> Create New Product</a>
            </div>
        </div>
    </div>
    @if ($message = Session::get('success'))
        <div>
            <p>{{ $message }}</p>
        </div>
    @endif
    <table>
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->description }}</td>
            <td>{{ $product->price }}</td>
            <td>
                <form action="{{ route('products.destroy',$product->id) }}" method="POST">
                    <a href="{{ route('products.show',$product->id) }}">Show</a>
                    <a href="{{ route('products.edit',$product->id) }}">Edit</a>
                    @csrf
                    @method('DELETE')
                    <button type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
    {!! $products->links() !!}
@endsection

create.blade.php

@extends('products.layout')
@section('content')
    <div>
        <div>
            <div>
                <h2>Add New Product</h2>
            </div>
            <div class>
                <a href="{{ route('products.index') }}"> Back</a>
            </div>
        </div>
    </div>
    @if ($errors->any())
        <div>
            <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>
            <div>
                <div>
                    <strong>Name:</strong>
                    <input type="text" name="name" placeholder="Name">
                </div>
            </div>
            <div>
                <div>
                    <strong>Description:</strong>
                    <textarea style="height:150px" name="description" placeholder="Description"></textarea>
                </div>
            </div>
            <div>
                <div>
                    <strong>Price:</strong>
                    <input type="text" name="price" placeholder="Price">
                </div>
            </div>
            <div>
                <button type="submit">Submit</button>
            </div>
        </div>
    </form>
@endsection

edit.blade.php

@extends('products.layout')
@section('content')
    <div>
        <div>
            <div>
                <h2>Edit Product</h2>
            </div>
            <div>
                <a href="{{ route('products.index') }}"> Back</a>
            </div>
        </div>
    </div>
    @if ($errors->any())
        <div>
            <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>
            <div>
                <div>
                    <strong>Name:</strong>
                    <input type="text" name="name" value="{{ $product->name }}" placeholder="Name">
                </div>
            </div>
            <div>
                <div>
                    <strong>Description:</strong>
                    <textarea style="height:150px" name="description" placeholder="Description">{{ $product->description }}</textarea>
                </div>
            </div>
            <div>
                <div class=”form-group">
                    <strong>Price:</strong>
                    <input type="text" name="price" value="{{ $product->price }}"
                        placeholder="Price">
                </div>
            </div>
            <div>
                <button type="submit">Submit</button>
            </div>
        </div>
    </form>
@endsection

Conclusion

In this tutorial, we have learned how to create a simple Laravel 9 CRUD application. We started by installing Laravel and setting up the database connection. Then, we created a migration for the products table and ran the migration to create the table in the database. Next, we created a model and a controller for the products. We implemented the CRUD functionality in the controller and created the views for the different actions. Finally, we tested our application by adding, editing, and deleting products. We also learned how to use Laravel's validation to validate the input data. Laravel provides an easy and elegant way to create web applications. Its built-in features such as routing, migration, and Eloquent ORM make it a popular choice for web development.

Categories

Latest Blogs

Ready to Amplify Your Services with our Premium White Label Web Design

Are you looking to expand your service offerings without the overhead of an in-house design team? Our white label web design services are the perfect solution. We provide top-notch, fully customizable web designs that seamlessly blend with your brand, allowing you to offer additional value to your clients.
Contact Us Today to Start Partnering with Our White Label Web Design Experts!

We love to provide services in the following cities

© 2024 · Prateeksha Web Design. Built with Gatsby All rights reserved | Privacy Policy
Designed by Prateeksha Web