Laravel application to perform crud operations

In this tutorial, we are going to create a Laravel application with CRUD operation. In programming, create, read, update, and delete are the four basic operations of data storage. We will give you a simple example of how to perform a CRUD operation in Laravel 8. Laravel is one of the most popular PHP-based frameworks for creating database-driven apps.

Laravel is described by its creators as the framework for web artisans. It's based on the MVC (Model-View-Controller) pattern and can be used for easily creating apps for making CRUD (Create, Retrieve/Read, Update, Delete) operations on a database.

So, let's create a Laravel application to perform CRUD operation step by step.

Create New Laravel Application

Let's begin to create our Laravel application with Jetstream authentication. First of all, create a new project.

You can create a fresh Laravel application with one of the below commands:

composer create-project --prefer-dist laravel/laravel Application_name
//If you already installed laravel globel installer
laravel new Application_name

Replace Application_name with your actual project name. 

Database Configuration

Let's configure a database for our application. If you don't have a database then create a new one. After creating the database open .env file from root directory of your project. if .env file is missing from project then copy content from .env.example and create file. The .env file defines many common environment variables

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=**********
DB_USERNAME=*********
DB_PASSWORD=*********
 Replace * with your actual configuration in above code.

Create Model and Migrations

Before starting let's understand what are model and migration.

What is a Model?

In Laravel, the Model is a class that represents the logical structure and relationship of the underlying database table. In Laravel, each of the database tables has a corresponding Model that allows us to interact with that table. Models give you a way to retrieve, insert, and update information into your data table. All of the Laravel Models are stored in the main app directory.

What is Migration?

Migrations are like version control for your database, allowing your team to define and share the application's database schema definition.

The Laravel Schema facade provides database-agnostic support for creating and manipulating tables across all of Laravel's supported database systems. Typically, migrations will use this facade to create and modify database tables and columns.

For creating the model and migration enter the below command to the terminal :

php artisan make:model Product -m

 This will create a Contact model and a migration file. In the terminal, we get an output similar to:

Model created successfully.
Created Migration: 2019_01_27_193840_create_contacts_table

 Open the app/models/Product.php file and update it accordingly:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $table = 'products';
    public $timestamps = true;

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

 Open the database/migrations/xxxxxx_create_contacts_table migration file and update it accordingly:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->unsignedBigInteger('price');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}

 We added the name, description, and price fields in the products table structure.

Migrating to Database

After defining our table structure, we have to create a table in the database using the below command :

php artisan migrate

Creating the Controller

Controllers are meant to group associated request-handling logic within a single class. In your Laravel project, they are stored in the app/Http/Controllers directory. The full form of MVC is Model View Controller, which acts as directing traffic among the Views and the Models. After creating the model and migrating our database. Let’s now create the controller for working with the Product model.

In your terminal, run the following command:

php artisan make:controller ProductController

 This command will generate a controller at app/Http/Controllers/ProductController.php and update it accordingly :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::latest()->paginate(5);

        return view('index', compact('products'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'price' => 'required'
        ]);

        Product::create($request->all());

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

    public function edit($id)
    {
        $product = Product::find($id);
        $products = Product::latest()->paginate(5);
        return view('index')->with(['product'=>$product,'products'=>$products]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'price' => 'required'
        ]);
        $product = Product::find($request->id);
        $product->update($request->all());

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

    public function destroy(Request $request)
    {
        $product = Product::find($request->id);
        $product->delete();
        return redirect()->route('products')->with('success', 'Product deleted successfully');
    }
}

Creating The Routes

What is Route?

Route is a way of creating a request URL for your application. These URLs do not have to map to specific files on a website. The best thing about these URLs is that they are both human-readable and SEO-friendly.

We have already created a method to handle CRUD for the products table. Now we need to provide implementations for these methods at specific URLs. For that, we have to create routes for particular functions. In laravel, All web routes must be added to a particular file routes/web.php. although you can create a custom route file and bind it to your application.

In this example, we are going to use the default route file so Open the routes/web.php file and update it accordingly

<?php

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

Route::get('/', function () {
    return view('welcome');
});

Route::get('/products', [ProductController::class, 'index'])->name('products');
Route::post('/products', [ProductController::class, 'store'])->name('products.store');
Route::get('/products/edit/{id}', [ProductController::class, 'edit'])->name('products.edit');
Route::post('/products/update', [ProductController::class, 'update'])->name('products.update');
Route::post('/products/delete', [ProductController::class, 'destroy'])->name('products.delete');

These route binds functions to specific URL which is listed below:

  1. GET /products, mapped to the index() method
  2. POST /products, mapped to the store() method
  3. GET /products/edit/{id}, mapped to the edit() method
  4. POST /products/update, mapped to the update() method
  5. POST /products/delete, mapped to the destroy() method

Creating Views

 View performs all frontend functionality of our application like displaying data, getting user input or getting requests. In this example, we are going to perform CRUD into single view you can use as many views as you want.

For Creating views, you can create a file with .blade.php extension at resources/views/ directory. For this example, Create index.blade.php file in that directory and alter it as below :

<html>
    <head>
        <title>Simple Laravel CRUD Example</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
        <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
        <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js"integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
    </head>
    <body>
        <div class="container">
            <div class="row" style="margin-top: 10px;">
                <div class="col-lg-12 margin-tb">
                    <div class="text-center">
                        <h1>Simple Laravel CRUD Example </h1>
                    </div>
                </div>
            </div>
            @if ($message = Session::get('success'))
                <div class="alert alert-success">
                    <p>{{$message}}</p>
                </div>
            @endif
            @if ($errors->any())
                <div class="alert alert-danger">
                    <strong>Error!</strong>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{$error}}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <div class="row">
                @if(isset($product))
                    <form action="{{route('products.update')}}" method="POST" >
                    <input type="hidden" name="id" value="{{$product->id}}" >
                @else
                    <form action="{{route('products.store')}}" method="POST" >
                @endif
                    @csrf
                    <div class="row mt-4">
                        <div class="col-xs-6 col-sm-6 col-md-6">
                            <div class="form-group">
                                <strong>Name:</strong>
                                <input type="text" name="name" class="form-control" placeholder="Name" value="{{isset($product) ? $product->name : ''}}">
                            </div>
                        </div>
                        <div class="col-xs-6 col-sm-6 col-md-6">
                            <div class="form-group">
                                <strong>Price:</strong>
                                <input type="number" name="price" class="form-control" placeholder="Put the price" value="{{isset($product) ? $product->price : ''}}">
                            </div>
                        </div>
                        <div class="col-xs-12 col-sm-12 col-md-12">
                            <div class="form-group">
                                <strong>Description:</strong>
                                <textarea class="form-control" rows="3" name="description"
                                    placeholder="description">{{isset($product) ? $product->name : ''}}</textarea>
                            </div>
                        </div>
                        <div class="col-xs-12 col-sm-12 col-md-12 text-right">
                            <button type="submit" class="btn btn-primary">Submit</button>
                            <a href="{{route('products')}}" class="btn btn-danger">Cancel</a>
                        </div>
                    </div>
                </form>
            </div>
            <table class="table table-bordered table-responsive-lg">
                <tr>
                    <th>No</th>
                    <th>Name</th>
                    <th>description</th>
                    <th>Price</th>
                    <th>Actions</th>
                </tr>
                @foreach ($products as $product)
                    <tr>
                        <td>{{$product->id}}</td>
                        <td>{{$product->name}}</td>
                        <td>{{$product->description}}</td>
                        <td>{{$product->price}}</td>
                        <td>
                            <form action="{{route('products.delete')}}" method="POST">
                                <a href="{{route('products.edit',$product->id)}}">
                                    <i class="fas fa-edit  fa-lg"></i>
                                </a>

                                @csrf
                                <input type="hidden" name="id" value="{{$product->id}}">
                                <button type="submit" title="delete" style="border: none; background-color:transparent;">
                                    <i class="fas fa-trash fa-lg text-danger"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                @endforeach
            </table>
            {!! $products->links() !!}
        </div>
    </body>
</html>

Running Laravel CRUD Application

For Running or Testing the CRUD application enter the below command :

php artisan serve

 It will produce output like the below :

Starting Laravel development server: http://127.0.0.1:8000
PHP 7.4.6 Development Server (http://127.0.0.1:8000) started

Open your browser and go to http://127.0.0.1:8000/products and test your application.