Simplified Laravel 9 AJAX Based CRUD Tutorial for Beginners

Last Updated: 22 Dec, 2022

In this simplified and easy tutorial you will learn how to create a AJAX Based CRUD application in Laravel 9 with the help of proper working examples. CRUD (Create, Read, Update, Delete) is a basic functionality that every web developer must aware of. It involves following operations that most frequently applies on any database entity:

CREATE: This operation helps us in creating a fresh record in database table.

READ: This operation is used to retrieve records from database tables  and may contains multiple WHERE conditions.

UPDATE: This operation deals with the record modification if necessary.

DELETE: With the help of this operation, we are able to remove any unwanted record from the database table.

We can follow below simple steps to create CRUD application in laravel 9:

Step 1: Install Fresh Laravel 9 Project

First of all, lets install and setup a fresh laravel 9 project. Open your terminal and run the below command:

composer create-project laravel/laravel l9ajaxcrud

Step 2: Configure Database in .env file

Next, lets update database configuration in .env file as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=l9ajaxcrud
DB_USERNAME={dbusername}
DB_PASSWORD={dbpassword}

Step 3: Create Database Migration

Next, let's create a migration file for customers table using following command:

php artisan make:migration create_customers_table --create=customers

This command will generate a file inside database/migrations directory. Open that file and modify it as follows:

<?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('customers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customers');
    }
};

Next, you have to run the below command that will execute the migration file and customers tables will be created in your database:

php artisan migrate

Step 4: Create a Resource Route for Customers

Next, lets create a resource route to perform customers CRUD operations. Open routes/web.php file and add following route in it:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomerController;
Route::get('/', function () {
    return view('welcome');
});
Route::resource('/customers', CustomerController::class);

Step 5: Create Customer Controller and Customer Model

Next, lets create a resource controller named CustomerController and model named Customer. In terminal, use following command to achieve this:

php artisan make:controller CustomerController --resource --model=Customer

When you run above command, 2 files will be created:

  • Controller file: app/Http/Controllers/CustomerController.php
  • Model file: app/Models/Customer.php

Let's open the CustomerController.php file and modify it as follows:

app/Http/Controllers/CustomerController.php

<?php
namespace App\Http\Controllers;
use App\Models\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $customers = Customer::paginate(5);
        $view_data['customers'] = $customers;
        return view('customers.index')->with($view_data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $view_data = [];
        return view('customers.create')->with($view_data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
        ]);
        $request_data = $request->all();
        Customer::create([
            'name' => $request_data['name'],
            'email' => $request_data['email']
        ]);
        return redirect()->route('customers.index')->with('success', 'Customer created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function show(Customer $customer)
    {
        $view_data['customer'] = $customer;
        return view('customers.show')->with($view_data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function edit(Customer $customer)
    {
        $view_data['customer'] = $customer;
        return view('customers.edit')->with($view_data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Customer $customer)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
        ]);
        $customer->update($request->all());
        return redirect()->route('customers.index')->with('success','Customer updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function destroy(Customer $customer)
    {
        $customer->delete();
        return redirect()->route('customers.index')->with('success', 'Customer deleted successfully');
    }
}

Let's open the Customer.php file and modify it as follows:

app/Models/Customer.php

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

class Customer extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'email'
    ];
}

Step 6: Create Blade Files for Customers

Next, let's create all the required view files in properly organized folder. We will need following files inside resources/views/customers directory:

  • master.blade.php
  • index.blade.php
  • create.blade.php
  • edit.blade.php
  • show.blade.php

resources/views/customers/master.blade.php

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Laravel 9 AJAX Based CRUD Tutorial</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
	<style type="text/css">
		.container{padding: 50px 220px;}@media only screen and (max-width: 767px){.container{padding: 15px;}}
	</style>
</head>
<body>
	<div class="container bg-info">
		@yield('content')
	</div>
</body>
</html>

resources/views/customers/index.blade.php

@extends('customers.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-8 text-danger"><h3>List of Customers</h3></div>
	<div class="col-12 col-md-4 text-end">
		<a class="btn btn-success" href="{{route('customers.create')}}">Create New Customer</a>
	</div>
</div>
<div class="row">
	@if(Session::get('error'))
	<div class="col-12">
		<div class="alert alert-danger alert-dismissible fade show" role="alert">
		  <strong>{{Session::get('error')}}!</strong>
		  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
		</div>
	</div>
	@endif
	<div class="col-12">
		<table class="table table-primary">
		  <thead>
		    <tr>
		      <th scope="col">#</th>
		      <th scope="col">Name</th>
		      <th scope="col">Email</th>
		      <th scope="col">Actions</th>
		    </tr>
		  	</thead>
		  	<tbody>
	  		@if($customers->count() > 0)
			  	@foreach($customers as $customer)
			    <tr>
			      <td>{{$loop->index + 1}}</td>
			      <td>{{$customer->name}}</td>
			      <td>{{$customer->email}}</td>
			      <td>
  	                <form action="{{ route('customers.destroy', $customer->id) }}" method="POST">
  	                	@csrf
                    	<a class="btn btn-info" href="{{ route('customers.show', $customer->id) }}">Show</a>
                    	<a class="btn btn-primary" href="{{ route('customers.edit', $customer->id) }}">Edit</a>
	                    @method('DELETE')
	                    <button type="submit" class="btn btn-danger">Delete</button>
                	</form>
			      </td>
			    </tr>
			    @endforeach
		    @else
		    <tr><td colspan="4">Customer not found!</td></tr>
		    @endif
		  	</tbody>
		</table>
		{!! $customers->links() !!}
	</div>
</div>
@endsection

resources/views/customers/create.blade.php

@extends('customers.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-8 text-danger"><h3>Create New Customer</h3></div>
	<div class="col-12 col-md-4 text-end">
		<a class="btn btn-success" href="{{route('customers.index')}}">List Of Customers</a>
	</div>
</div>
<div class="row">
	@if($errors->any())
	<div class="col-12">
		<div class="alert alert-danger alert-dismissible fade show" role="alert">
		  <strong>Some error occured!</strong>
		  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
		  <ul>
		  	@foreach($errors->all() as $error)
		  	<li>{{$error}}</li>
		  	@endforeach
		  </ul>
		</div>
	</div>
	@endif
	<div class="col-12">
		<form method="POST" action="{{route('customers.store')}}">
			@csrf
			<div class="mb-3">
			    <label for="name" class="form-label">Name</label>
			    <input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
		  	</div>
		  	<div class="mb-3">
			    <label for="email" class="form-label">Email</label>
			    <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
		  	</div>
		  	<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	</div>
</div>
@endsection

resources/views/customers/edit.blade.php

@extends('customers.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-8 text-danger"><h3>Edit Customer</h3></div>
	<div class="col-12 col-md-4 text-end">
		<a class="btn btn-success" href="{{route('customers.index')}}">List of Customers</a>
	</div>
</div>
<div class="row">
	@if($errors->any())
	<div class="col-12">
		<div class="alert alert-danger alert-dismissible fade show" role="alert">
		  <strong>Some error occured!</strong>
		  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
		  <ul>
		  	@foreach($errors->all() as $error)
		  	<li>{{$error}}</li>
		  	@endforeach
		  </ul>
		</div>
	</div>
	@endif
	<div class="col-12">
		<form method="POST" action="{{route('customers.update', $customer->id)}}">
			@csrf
			@method('PUT')
			<div class="mb-3">
			    <label for="name" class="form-label">Name</label>
			    <input type="text" class="form-control" id="name" name="name" value="{{$customer->name}}" placeholder="Enter name">
		  	</div>
		  	<div class="mb-3">
			    <label for="email" class="form-label">Email</label>
			    <input type="email" class="form-control" id="email" name="email" value="{{$customer->email}}" placeholder="Enter email">
		  	</div>
		  	<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	</div>
</div>
@endsection

resources/views/customers/show.blade.php

@extends('customers.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-8 text-danger"><h3>Customer Details</h3></div>
	<div class="col-12 col-md-4 text-end">
		<a class="btn btn-success" href="{{route('customers.index')}}">List of Customers</a>
	</div>
</div>
<div class="row">
	<div class="col-12 mb-3">
		<strong>Customer Name: {!! $customer->name !!}</strong>
	</div>
	<div class="col-12 mb-3">
		<strong>Customer Email: {!! $customer->email !!}</strong>
	</div>
</div>
@endsection

Step 7: Start Laravel Development Server and Run Application in browser

That's all. You are good to go. Let's run the application using below command:

php artisan serve

Next, in your browser, open below URL:

http://localhost:8080/customers

Simplified Laravel 9 AJAX Based CRUD Tutorial for Beginners

 

Thank You, Please Share.

Recommended Posts

Simplified Laravel 9 REST API Tutorial using Sanctum  Authentication

Simplified Laravel 9 REST API Tutorial using Sanctum Authentication

In this simplified tutorial, you will learn the simplest way to create a REST API application in Laravel 9 that will be authenticated using Laravel Sanctum.

Laravel 10 CRUD Application Tutorial for Beginners

Laravel 10 CRUD Application Tutorial for Beginners

In this simple and comprehensive tutorial you are going to learn how to install Laravel 10 and create a New Laravel 10 CRUD Application.

IMAGE

How to Install and Configure Vue 3 Application in Laravel 10

This tutorial will show you How To Install and Configure a basic Vue 3 Application in Laravel 10 using Vite 3.