Laravel get data from database with ajax php example

Php Laravel get data from database with ajax example

In this article, i am going to share you  php Laravel get data from database with ajax. As provides a faciliity to load data without refeshing whole page. Through ajax, we can update only some specific part of the web page.

Sometimes we only need to update or change only some part of the web page then we can reload or refresh the whole page but it will take more time and more data for same thing. Whole page load is not a good practice for heavy pages or website.

So to overcome the problem of page load data and time, we can use ajax. Ajax is basically stands for Asynchronous JavaScript and XML. Here, we are going to create an example to demostrate ajax call in php laravel web application.

Here, i am giving some very simple steps to implement ajax request in your laravel application or project from scratch. You just need to follow these steps one by one. So now, without wasting our time let’s start the steps.

Step 1: Install laravel Application

In this step, we will need to install laravel application using composer command. If you have already installed, you can jump to the next step. So for installing new project you just need to run the following composer command as given below.

composer create-project --prefer-dist laravel/laravel blog

I am giving a name as blog to this application. You can give your own what you like.

Step 2: Configure database and create model

In this step, let’s connect to ourr laravel application to the database. So, open .env file in the root directory and update with correct database details.

DB_DATABASE=put your database name here
DB_USERNAME=put database username here
DB_PASSWORD=put database password here

Now, we will need to create migration for database table. So, open terminal or command prompt and run the following command.

php artisan make:migration create_users_table

Now, open the migration file and update the code to add table structure like below.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('users', function (Blueprint $table) {
     * Reverse the migrations.
     * @return void
    public function down()

After adding the table structure, run migration command to create table using the artisan command below.

php artisan migrate

Step 3: Create Routes

In step, we will create two routes for get all user’s data and a user’s details. So open routes/web.php file and put the following route as mentioned below.

Route::get('/users', 'AjaxController@index');

Step 4: Create Controller

Now, we will create AjaxController using the artisan command as given below.

php artisan make:controller AjaxController

After running the above command, a AjaxController.php file would be created. So open it and put the following code as witten below.


namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Redirect,Response;
class AjaxController extends Controller{
  public function index(){
    return view('get-ajax-data');
  public function getUserDetails($id = 0){
    // get records from database
      $arr['data'] = User::orderBy('id', 'asc')->get(); 
      $arr['data'] = User::where('id', $id)->first();
    echo json_encode($arr);

Step 5: Create View

Now, we will need to create view files. So create get-ajax-data.blade.php  file and put the code as shown in below code.


<!doctype html>
<title>Php Laravel get data from database with ajax example</title>
</head> <body> <input type='text' id='search' name='search' placeholder='Enter userid'> <input type='button' value='Search' id='search-btn'> <br/> <input type='button' value='Get all records' id='get-all-record'> <table border='1' id='user-data' style='border-collapse: collapse;'> <thead> <tr> <th></th> <th>Username</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody></tbody> </table> <!-- Script --> <script src=""></script> <!-- jQuery CDN --> <script type='text/javascript'> $(document).ready(function(){ // Get all records $('#get-all-record').click(function(){ getRecords(0); }); // Search by user id $('#search-btn').click(function(){ var userid = Number($('#search').val().trim()); if(userid > 0){ getRecords(userid); } }); }); function getRecords(id){ $.ajax({ url: 'user-details/'+id, type: 'get', dataType: 'json', success: function(response){ var len = 0; $('#user-data tbody').empty(); // Empty <tbody> if(response['data'] != null){ len = response['data'].length; } if(len > 0){ for(var i=0; i<len; i++){ var id = response['data'][i].id; var username = response['data'][i].username; var name = response['data'][i].name; var email = response['data'][i].email; var tr_str = "<tr>" + "<td align='center'>" + (i+1) + "</td>" + "<td align='center'>" + username + "</td>" + "<td align='center'>" + name + "</td>" + "<td align='center'>" + email + "</td>" + "</tr>"; $("#user-data tbody").append(tr_str); } }else if(response['data'] != null){ var tr_str = "<tr>" + "<td align='center'>1</td>" + "<td align='center'>" + response['data'].username + "</td>" + "<td align='center'>" + response['data'].name + "</td>" + "<td align='center'>" + response['data'].email + "</td>" + "</tr>"; $("#user-data tbody").append(tr_str); }else{ var tr_str = "<tr>" + "<td align='center' colspan='4'>No record found.</td>" + "</tr>"; $("#user-data tbody").append(tr_str); } } }); } </script> </body> </html>

Step 6: Run Development Server

After doing all the steps from step 1 to step 5, we have completed the task that is to get data from database with ajax. Now we can run the developement server using the artisan command given below.

php artisan serve

After that now you can copy and paste the url given below in your web browser to see the result what you have done till now.

You can also read laravel CRUD operations with example by clicking the link below.

Laravel CRUD operation (Create, Read, Update, Delete) with example