Laravel 7 Ajax Get Data From Database

Laravel 7 Ajax Get Data From Database

Laravel ajax getting data from the database. In this tutorial, we would like to share with you, how to get or fetch data using ajax request in laravel web applications.

In this post, we would love to share with you how you can get/fetch single and multiple records from mysql database using ajax in laravel web applications.

Laravel Ajax Get Data From Database

Just follow the below steps and get data using ajax in laravel:

  • First Install New Laravel Setup
  • Configure .env file
  • Create One Model and Migration
  • Make Route
  • Generate Controller by command
  • Create Blade View
  • Start Development Server

Step 1: First Install New Laravel Setup

In this step, we will download a new laravel setup. Use the below following command and download it :

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

Step 2: Configure .env file

Next Go to your project root directory, find .env file and setup database credential here :

 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

Next go to app/datatabase/migrations and open users migration file and put the below code here :

public function up()
 {
     Schema::create('users', function (Blueprint $table) {
         $table->increments('id');
         $table->string('username')->nullable();
         $table->string('name')->nullable(); 
         $table->string('email')->nullable();
         $table->timestamps();
     });
 }

Before we run php artisan migrate command go to app/providers/AppServiceProvider.php and put the below code :

...
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
...

Next migrate the table using the below command :

php artisan migrate

Step 3: Make Route

Create two routes like below for getting data from database and display list. So routes/web.php file and update the below routes in your file:

//routes

Route::get('/users', 'AjaxController@index');
Route::get('/getData/{id}','AjaxController@getData');

Step 4: Generate Controller by Command

Now we will create a controller name AjaxController.php. Use the below command for generate controller

php artisan make:controller AjaxController

Next we will use only four methods the from resource controller. Next open your controller and replace the methods given in below :

<?php

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 getData($id = 0){
    // get records from database

    if($id==0){
      $arr['data'] = User::orderBy('id', 'asc')->get(); 
    }else{
      $arr['data'] = User::where('id', $id)->first();
    }
    echo json_encode($arr);
    exit;
  }
}

Step 5: Create blade view :

In this step, we will create one blade file name get-ajax-data.blade.php. So go to resource/views/ and create blade view file and update the below code into your file:

<!doctype html>
<html>
   <body>
     <input type='text' id='search' name='search' placeholder='Enter userid 1-27'>
     <input type='button' value='Search' id='btnSearch'>
     <br/>
     <input type='button' value='Fetch all records' id='fetchAllRecord'>
     
     <table border='1' id='userTable' style='border-collapse: collapse;'>
       <thead>
        <tr>
          <th>S.no</th>
          <th>Username</th>
          <th>Name</th>
          <th>Email</th>
        </tr>
       </thead>
       <tbody></tbody>
     </table>

     <!-- Script -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- jQuery CDN -->

     <script type='text/javascript'>
     $(document).ready(function(){

       // Fetch all records
       $('#fetchAllRecord').click(function(){
              fetchRecords(0);
       });

       // Search by userid
       $('#btnSearch').click(function(){
          var userid = Number($('#search').val().trim());
                
      if(userid > 0){
        fetchRecords(userid);
      }

       });

     });

     function fetchRecords(id){
       $.ajax({
         url: 'getData/'+id,
         type: 'get',
         dataType: 'json',
         success: function(response){

           var len = 0;
           $('#userTable 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>";

               $("#userTable 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>";

              $("#userTable tbody").append(tr_str);
           }else{
              var tr_str = "<tr>" +
                  "<td align='center' colspan='4'>No record found.</td>" +
              "</tr>";

              $("#userTable tbody").append(tr_str);
           }

         }
       });
     }
     </script>
  </body>
</html>

Step 6: Run Development Server

In this step, we will use the php artisan serve command . It will start your server locally

 php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://127.0.0.1:8000/users

Conclusion

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *