We'll create a basic application of handling AJAX requests in Laravel that fetches user data asynchronously .
1. Setup Laravel Project:
If you haven't created a Laravel project yet, you can do so using Composer:
composer create-project --prefer-dist laravel/laravel ajax-example cd ajax-example
2. Create Database and Model:
Create a database, update the .env file with your database credentials, and run migrations.
php artisan migrate
Create a model for the User:
php artisan make:model User -m
In the generated migration file (database/migrations/xxxx_xx_xx_create_users_table.php), add some columns to the users table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
Run migrations:
php artisan migrate
3. Create Controller:
Create a controller for handling AJAX requests:
php artisan make:controller UserController
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function getUsers()
{
$users = User::all();
return response()->json($users);
}
}
4. Create Route:
Define a route in routes/web.php or routes/api.php:
use App\Http\Controllers\UserController;
Route::get('/get-users', [UserController::class, 'getUsers']);
5. Create Blade View:
Create a Blade view (resources/views/welcome.blade.php) with a button to trigger the AJAX request:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>AJAX Example</title>
</head>
<body>
<button id="fetch-users">Fetch Users</button>
<ul id="user-list"></ul>
<script src="{{ asset('js/app.js') }}"></script>
<script>
document.getElementById('fetch-users').addEventListener('click', function () {
fetchUsers();
});
function fetchUsers() {
fetch('/get-users')
.then(response => response.json())
.then(users => {
const userList = document.getElementById('user-list');
userList.innerHTML = '';
users.forEach(user => {
const listItem = document.createElement('li');
listItem.textContent = user.name;
userList.appendChild(listItem);
});
})
.catch(error => console.error(error));
}
</script>
</body>
</html>
6. Run the Application:
Run the development server:
php artisan serve
Visit http://127.0.0.1:8000 in your browser. Click the "Fetch Users" button, and you should see the list of users fetched asynchronously.

Comments