Laravel 10 - Tutorial to create CRUD Application


Today, I'll show you an example of how to perform CRUD operations in Laravel 10. We'll be building a simple CRUD application using Laravel 10, suitable for beginners. This example will demonstrate how to create, read, update, and delete data in Laravel 10.
 

Understanding CRUD:
CRUD stands for Create, Read, Update, and Delete. It's a term used in computer programming to describe the essential functions needed for managing data in an application.
 

In this example, we'll be creating a product management system using Laravel 10. We'll start by setting up a 'products' table with 'name' and 'detail' columns through a Laravel 10 migration. Then, we'll create routes, a controller, views, and a model for the product module. Additionally, we'll use Bootstrap 5 for the design. Let's get started by following the steps below.

Step 1: Setup & Install Laravel 10

First, we'll begin by setting up a new Laravel 10 application. If you've already made a project, you can skip this part. Just make sure you have Laravel installed on your computer. If it's not installed yet, you can do it using a tool called Composer.

composer create-project laravel/laravel example-crud


Step 2: Configure the Database


In this tutorial, we'll be using a MySQL database to create the CRUD application. Now, we need to tell the application how to connect to this database. To do this, open the .env file and add the following details as shown below:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Step 3: Create Migration for table products

Now, we're going to use Laravel migration to create the "products" table. To do this, use the following command:

php artisan make:migration create_products_table --create=products

You'll now see a new file at this location: "database/migrations/xxxx_xx_xx_create_products_table.php". Open the file and add the following code to finish defining the table.

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->text('price')
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};

 

Next, you need to execute this migration using the following command:

php artisan migrate


Step 4: Create Controller and Model

To make a new resource controller named ProductController, use the following command:

 

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

Once you run the command, you'll find a new controller at "app/Http/Controllers/ProductController.php".

In this controller, by default, seven methods will be created:

  1. index()
  2. create()
  3. store()
  4. show()
  5. edit()
  6. update()
  7. destroy()

Let's copy the code below and paste it into the ProductController.php file.

app/Http/Controllers/ProductController.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: Create Route

Now, let's add a resource route in the "routes/web.php" file. Include the following route:

routes/web.php

Route::resource('products', ProductController::class);


Step 6: Create Blade Files ( View )

In the final step, we'll be creating blade files. First, we'll make a layout file, then create a new folder named "products". Inside it, we'll add the blade files for the CRUD app. Here are the files you need to create:

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

Let's start creating the above mentioned blade view files.

 

resources/views/products/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 - Laravel 10 tutorial to create CRUD Application</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>

Now create the index page.

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 10 - Laravel 10 tutorial to create CRUD Application</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

Now, create the view to edit the page. 

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

Now create a page to show the product listing.

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


Step 7: Run Laravel 10 App and Test Your Application

Finally, to start your Laravel app, run the following command:

 

php artisan serve

After running this command, your Laravel application will start and be accessible at the following URL:

http://localhost:8000/products

Remember, this is a basic outline to get you started. Depending on your specific requirements, you might need to make additional adjustments or add more features to your CRUD application.


Recent Questions

Recent Tutorials
Laravel 10 - Send mail using AWS SES

Learn to send Email using Laravel 10 with AWS SES service.

Laravel 10 - Tutorial on how to use jQuery to validate the form

Learn how to use jQuery in Laravel 10 to validate the form

Laravel - How to upload file to AWS S3 Bucket

Explore how we can upload file using the laravel on Amazon S3 bucket.

How to Make an AWS S3 Bucket Public

Learn how we can make an AWS S3 bucket public

Laravel 10 - Tutorial to create CRUD Application

Learn to create crud application using laravel 10. Step by step guidance will help to understand the concept of crud.