Laravel

How to use AJAX in Laravel 10 Using Vue.js

in this post, I will discuss how to integrate Ajax (Asynchronous JavaScript and XML) with Laravel 10. Two common libraries support AJAX call: jQuery and Vue.js, I am using vue.js to create AJAX calls to filter data and display into the listing page.

It allows for better responsiveness, real-time updates, and an easier-to-use search functionality. I have already shared tutorial: CRUD Functionality in Laravel

What’s Ajax

Ajax is a method that allows for the refresh of a webpage’s content without the need for a complete page reload. This technique facilitates dynamic, asynchronous communication between the client and server, It helps developers to design web applications that are more responsive and interactive.

What is Laravel

Laravel is a widely-used open-source PHP web application framework, that allows to creation of dynamic and interactive modern web applications.

Implementing AJAX in Laravel

We’ll look at a complete example of Laravel Ajax integration with Vue.js.

Setting Up the Laravel Project

Let’s start to create a new project, assuming you have Composer installed, Open your terminal to create your Laravel application by running the following command.

composer create-project --prefer-dist laravel/laravel laravel-ajax-vue-search
cd laravel-ajax-vue-search

Create a Database and Table
Let’s create a ‘test’ database and create a new migration file using the below command:

php artisan make:migration create_employees_table --create=employees

The above command will generate a migration file into the "database/migrations" directory and define the table schema as follows:

// database/migrations/YYYY_MM_DD_create_employees_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateEmployeesTable extends Migration
{
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
   $table->string('name');
   $table->integer('salary');
      $table->integer('age');
   $table->timestamps();
        });
    }

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

Run the below migration command to create the database table into the database:

php artisan migrate

Connect Your database with Test db:

You need to edit your application’s .env file at the root of your Laravel application. Locate the variables prefixed with DB_ and edit them with your database credentials:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3036
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=pass

Replace “localhost,” “3036,” “test,” “root,” and “pass” with the actual values specific to your MySQL host configuration.

Creating a Model and Seeder

Let’s create a model for the "employees" table and a seeder to populate it with sample data. Run the following commands:

php artisan make:model Employee
php artisan make:seeder CreateEmployeesTable

Line 1: The command will create a model file in "app/Models/Employee.php".
Line 2: It will create "EmployeesTableSeeder.php" file in the "database/seeders" directory:

Define the model:

Related Post
// app/Models/Employee.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'salary', 'age'];
}

Define Seeder logic:

// database/seeders/EmployeesTableSeeder.php

use Illuminate\Database\Seeder;
use App\Models\Employee;

class EmployeesTableSeeder extends Seeder
{
    public function run()
    {
        Employee::create(['name' => 'Adam', 'age' => 25, 'salary' => 2345]);
        Employee::create(['name' => 'Parvez', 'age' => 25, 'salary' => 1345]);
    }
}

To add entries to the "employees" table, run the seeder:

php artisan db:seed --class=EmployeesTableSeeder

Creating Routes and Controller

Let’s set up routes and a controller for handling the Ajax requests. Open the web.php file in the "/routes" directory and define the routes:

// routes/web.php

use App\Http\Controllers\EmployeeController;

Route::get('/', [EmployeeController::class, 'index']);
Route::get('/employees', [EmployeeController::class, 'getEmployees']);
Route::get('/search', [EmployeeController::class, 'search']);

Generate a controller named “EmployeeController” with the following command:

php artisan make:controller EmployeeController

The above command will create a controller file "app/Http/Controllers/EmployeeController.php" and define the methods:

// app/Http/Controllers/EmployeeController.php

namespace App\Http\Controllers;

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

class EmployeeController extends Controller
{
    public function index()
    {
        return view('index');
    }

    public function getEmployees()
    {
        $emps = Employee::latest()->get();

        return response()->json($emps);
    }

    public function search(Request $request)
    {
        $query = $request->input('query');

        $emps = Employee::where('name', 'LIKE', "%$query%")->get();

        return response()->json($emps);
    }
}

Creating Laravel Views

Let’s create the views for our Laravel application. Create a file named "index.blade.php" in the "resources/views" directory. The file HTML structure is as follows:

<!-- resources/views/index.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel Ajax Vue Search Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>

<div id="app" class="container mt-5">
    <h2>Live Employee Search</h2>

    <div class="form-group">
        <input type="text" class="form-control" v-model="searchQuery" @input="searchEmp" placeholder="Search employee">
    </div>

    <ul class="list-group">
        <li class="list-group-item" v-for="emp in emps" :key="emp.id">
            @{{ emp.name }}
        </li>
    </ul>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="{{ asset('js/app.js') }}"></script>

</body>
</html>

In the above code, We’ve included the Bootstrap CSS for styling and created a simple form with an input field for the live search functionality. An unordered list of the search results is displayed.

Implementing Ajax in Laravel Using Vue.js

Create a JavaScript file named "app.js" in the “public/js” directory, an add below code into this file:

// public/js/app.js

const app = new Vue({
    el: '#app',
    data: {
        emps: [],
        searchQuery: '',
    },
    mounted() {
        this.getEmployees();
    },
    methods: {
        getEmployees() {
            axios.get('/employees')
                .then(response => {
                    this.emps = response.data;
                })
                .catch(error => {
                    console.log(error);
                });
        },
        searchEmployees() {
            axios.get('/search', { params: { query: this.searchQuery } })
                .then(response => {
                    this.emps = response.data;
                })
                .catch(error => {
                    console.log(error);
                });
        },
    },
});

in the above code, We have defined searchEmployees method that triggered on every input change in the search input field. The method of making an Ajax request to the "/search" endpoint with the current search query.

The server responds with a JSON array of matching employees and updates the UI to show the search results dynamically.

Import the JavaScript file in the view:

Open the "resources/views/index.blade.php" file and include the JavaScript file:

<!-- resources/views/index.blade.php -->

<!-- ... (existing code) ... -->

<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="{{ asset('js/app.js') }}"></script>

</body>
</html>

Run the Laravel Application

Let’s start the development server b y running the following command:

php artisan serve

Open your web browser and navigate to http://localhost:8000/ to see the list of employees.

Conclusion

We have implemented Ajax functionality with Vue in Laravel 10 and also added live search functionality in a web application using AJAX. You can use Ajax to create CRUD features in your application.

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories