In this tutorial you will learn about the Laravel 7 Ajax Get Data From Database and its application with practical example.
In this Laravel ajax get data from the database tutorial I will show you how to fetch data from database using ajax in laravel applications. In this tutorial you will learn to use ajax in laravel. In this article I will demonstrate you how to fetch records from database using ajax in laravel. Using ajax you can fetch data from database without reloading page in laravel. In this step by step guide you will understand laravel ajax request implementation.
Laravel 7 Ajax Get Data From Database
- 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
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: Configure .env file
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
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 :
1 2 3 4 5 6 7 8 9 10 |
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 :
1 2 3 4 5 6 7 8 9 |
... use Illuminate\Support\Facades\Schema; .... function boot() { Schema::defaultStringLength(191); } ... |
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan migrate |
Step 3: Make Route
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 |
//routes Route::get('/users', 'AjaxController@index'); Route::get('/getData/{id}','AjaxController@getData'); |
Step 4: Generate Controller by Command
Now, lets create a controller named AjaxController using command given below –
1 |
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?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 a blade file name get-ajax-data.blade.php. Now, go to resource/views/ and create a blade file and put following code in it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
<!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
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://127.0.0.1:8000/users |