Laravel 9 fetch data using ajax example; In this tutorial you will learn step by step guide on how to get/retrive data from database in Laravel with AJAX call.
This tutorial will show you how to easily get records from database in laravel using ajax and show in a model without reload or refresh page. Here we have a user list and we want to show the user info in model using ajax request.
Laravel Get Data from Database with Ajax
AJAX is primarily used to make flawless HTTP requests to read, write, update, and delete the data from the server. AJAX is a tool that makes the consensus between the client and the server.
The usage of AJAX is from the primordial time, obviously from the web development perspective. Follow the steps to getting data from database using ajax in laravel application.
- Step 1: Install Laravel App
- Step 2: Connect App to Database
- Step 3: Create Database Migration
- Step 4: Make Routes
- Step 5: Create Controller
- Step 6: Create Blade Views
- Step 7: Start Development Server
Install Laravel App
We have to run the given below command to install a fresh Laravel application, this app will be the sacred canon for fetch data from database in Laravel Ajax example.
composer create-project --prefer-dist laravel/laravel laravel-ajax
Head over to project directory, or you can simultaneously execute following command with above command followed by double && symbol.
cd laravel-ajax
Connect App to Database
Ultimately, we have to define the database details in the .env
file, make the consensus between laravel app and MySQL database.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here
Run Database Migration Command
In this step, execute the following command to create tables into database:
php artisan migrate
Make Routes
Define route; it is one of the foundational steps that directly communicates with the controller that we created earlier, open routes/web.php, and paste the following code.
use App\Http\Controllers\UserController;
Route::get('users', [UserController::class, 'index']);
Route::get('show-user', [UserController::class, 'show']);
Create Controller
Execute the following command to create the user controller for handling the form and ajax request.
php artisan make:controller UserController
Paste the following code in the newly created controller in app/Http/Controllers/UserController.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::orderBy('id','desc')->paginate(10);
return view('users', compact('users'));
}
public function show($id)
{
$user = User::find($id);
return response()->json($user, 200);
}
}
Create Blade Views
Let us create the view for showing you how to use AJAX for getting records in the Laravel application from database precisely. Head over to resources/views folder and create users.blade.php file.
resources\views\users.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Ajax Data Fetch Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
<h1>Laravel Ajax Data Fetch Example</h1>
<table class="table table-bordered data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<button
onclick="showUser({{$user->id}})"
class="btn btn-info"
>Show</button>
</td>
</tr>
@endforeach
</tbody>
</table>
{{ $users->links() }}
</div>
<!-- Modal -->
<div class="modal fade" id="userShowModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="userShowModalLabel">Show User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p><strong>ID:</strong> <span id="user-id"></span></p>
<p><strong>Name:</strong> <span id="user-name"></span></p>
<p><strong>Email:</strong> <span id="user-email"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function showUser(userId) {
$.ajax({
url: "users/" + userId,
type:"get",
success:function(response){
$('#userShowModal').modal('show');
$('#user-id').text(response.id);
$('#user-name').text(response.name);
$('#user-email').text(response.email);
},
error: function(error) {
console.log(error);
}
});
}
</script>
</html>
Generate Test Records
Now we need to insert some fake records to database for testing bases:
Execute the following command on command prompt to generate or create dummy data using tinker and factory command:
php artisan tinker
User::factory()->count(20)->create()
Run Your Application
You need to start the application by executing the below command:
php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080
You can test the app on the following URL:
http://127.0.0.1:8000/users
In this tutorial, we have learned Laravel get records from database using ajax request. I hope you liked this tutorial, please share this tutorial with other developers likewise help me to bring more content like this.