Share this:

Laravel is one of the most popular PHP frameworks used for web application development. It’s known for its simplicity, flexibility, and scalability. With Laravel, you can easily create CRUD (Create, Read, Update, Delete) applications that allow users to perform basic database operations.

In this tutorial, we will be creating a CRUD application using Laravel 10. We will be using Laravel’s built-in features such as the Eloquent ORM, Blade templating engine, and Laravel’s routing system to create a simple application that allows users to perform CRUD operations on a database.

By the end of this tutorial, you will have a better understanding of how to use Laravel to build a CRUD application and how to use Laravel’s features to make your application more efficient and secure. Let’s get started!

Steps to create CRUD Application using Laravel 10 :

Step 1: Install Laravel 10 Application

  1. Install Composer: Laravel uses Composer, a dependency manager for PHP. To install Composer, visit the official Composer website and follow the installation instructions for your operating system.
  2. Install Laravel Installer: Laravel has its own installer that helps you to create a new Laravel project quickly. To install the Laravel installer, open a terminal or command prompt and run the following command: composer global require laravel/installer
  3. Create a new Laravel project: Once you have installed the Laravel installer, you can use it to create a new Laravel project. To create a new project, navigate to the directory where you want to create the project and run the following command: laravel new <project-name> Replace <project-name> with the name of your project. This command will create a new Laravel project in a directory with the same name as your project.
  4. Serve your Laravel application: To serve your Laravel application, navigate to the root directory of your project and run the following command: php artisan serve This will start a development server on http://localhost:8000, and you can access your Laravel application by visiting this URL in your web browser.

Step 2: Database Configuration

Database configuration is an essential step in building a Laravel application as most web applications require storing data in a database. Laravel makes it easy to configure a database by providing a simple configuration file that allows you to specify your database settings.

To configure your database in Laravel, navigate to the .env file in the root directory of your project. This file contains environment variables that Laravel uses to configure various aspects of your application, including the database.

In the .env file, you can set the database driver, database name, database username, database password, and host. Laravel supports a variety of database drivers such as MySQL, PostgreSQL, SQLite, and SQL Server.

Once you have set your database configuration in the .env file, Laravel will automatically use these settings to connect to your database. You can now use Laravel’s built-in Eloquent ORM to interact with your database and perform CRUD operations.

It is important to ensure that your database credentials are secure, especially if you plan to deploy your application to a production environment. You can use Laravel’s built-in encryption and hashing features to secure your sensitive information in the .env file.

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

Step 3: Create Migration

Open a terminal or command prompt and navigate to the root directory of your Laravel project.

Run the following command to create a new migration for the products table:

php artisan make:migration create_products_table

This will create a new migration file in the database/migrations directory.

Open the newly created migration file in a code editor. By default, the migration file will have two methods: up() and down(). The up() method is used to define the schema for the new table, and the down() method is used to undo the changes made by the up() method.

In the up() method, use the Laravel Schema Builder to define the schema for the new products table. Here’s an example schema definition:

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

This schema will create a new products table with the following columns: id, name, detail and timestamps.

Save the migration file and run the following command in your terminal to execute the migration:

php artisan migrate

This will run the migration and create the new products table in your database.

Step 4: Create Controller and Model

In this step, now we should create new resource controller as ProductController. So run bellow command and create new controller. bellow controller for create resource controller.

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

After the bellow command, you will find a new file in this path “app/Http/Controllers/ProductController.php”.

In this controller will create seven methods by default as methods: index(), create(), store(), show(), edit(), update(), destroy()

So, let’s copy bellow code and put on 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: Create Resources Routes

Here, we need to add resource route for product crud application. so open your “routes/web.php” file and add following route.

routes/web.php

<?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 5: Creating Blade Files

We are going to create layout.blade.php, index.blade.php, create.blade.php, edit.blade.php, show.blade.php blade files:

So let’s just create the file one by one by adding the following code.

resources/views/products/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Create CRUD Application using Laravel 10 - LaravelTuts.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

@extends('products.layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Create CRUD Application using Laravel 10 - LaravelTuts.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

Step 6: Testing

Now everything is done! we are going to test our application by running the following command:

php artisan serve

This will start the laravel server.

Now open any web browser and open the following link to test the application.

http://localhost:8000/products

Hope this help you creating you CRUD application using laravel 10.

Share this:

Categorized in: