Laravel 8 Ajax Get Data From Database Example

https://laratutorials.com/laravel-8-ajax-get-data-from-database-example/

Laravel 8 Ajax Get Data From Database Example

Laravel 8 ajax get/fetch data from database. In this post, i will show from scratch on how to get or retrieve data from database using ajax in laravel.

If you want to fetch/get data from database using jQuery ajax without reload the whole web page. And want to display on html page.

So, in this example post, i will use jQuery ajax to fetch data from database and display in blade view (html page). As well as how to use ajax request(GET/POST) in laravel to retrieve data from database

How to Retrieve Data From Database using Ajax in Laravel

  • Step 1 – Install Laravel 8 Application

  • Step 2 – Configuring Database using Env File

  • Step 3 – Generate Dummy Record Into Database

  • Step 4 – Create Routes

  • Step 5 – Creating Ajax Get Data Controller

  • Step 6 – Create Blade File to Display Data

  • Step 7 – Start Development Server

  • Step 8 – Run Laravel 8 Ajax Get Data From Database App On Browser

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Configuring Database using Env File

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=db nameDB_USERNAME=db user nameDB_PASSWORD=db password

Step 3 – Generate Dummy Record Into Database

In step 3, Generate dummy records into database table users. So, navigate database/seeders/ directory and open DatabaseSeeder.php file. Then add the following two line of code it:use App\Models\User;User::factory(100)->create();

After that, open command prompt and navigate to your project by using the following command:

cd / LaravelAjaxGet

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Next, run the following database seeder command to generate dummy data into database:

php artisan db:seed

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:<?phpuse Illuminate\Support\Facades\Route;use App\Http\Controllers\AjaxGetDataController;/*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/Route::get('/', function () { return view('welcome');});Route::get('ajax-get-data-form', [AjaxGetDataController::class, 'index']);Route::post('get-data-from-db', [AjaxGetDataController::class, 'retrieve']);

Step 5 – Creating Controller

In step 5, create form controller by using the following command:

php artisan make:controller AjaxGetDataController

The above command will create AjaxGetDataController.php file, which is located inside LaraveljQuery/app/Http/Controllers/ directory.

So open AjaxGetDataController.php file and add the following code into it:<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Models\User;class AjaxGetDataController extends Controller{ public function index() { return view('ajax-get-data-form'); } public function retrieve(Request $request) { $term = $request->str; $data = []; if(!empty($term)){ $data = User::where('name', 'LIKE', "%{$term}%") ->orWhere('email', 'LIKE', "%{$term}%") ->first(); } $res = true; if(!$data){ $data['msg'] = 'No Record Found'; $res = false; } return response()->json(['success' => $res, 'data' => $data]); }}

Step 6 – Create Blade File For Contact Form

In step 6, create new blade view file that named ajax-get-data-form.blade.php inside resources/views directory for ajax get data from database.

And the following jQuery and ajax code will get and display data from database in laravel:<script> $(document).ready(function($){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('body').on('click', '#search', function () { var str = $("#query").val(); $("#search").html('Please Wait...'); // ajax $.ajax({ type:"POST", url: "{{url('get-data-from-db')}}", data: { str: str }, dataType: 'json', success: function(res){ if(res.success == true){ $(".jumbotron").removeClass("d-none"); $("#msg").addClass("d-none"); $('#id').html(res.data.id); $('#name').html(res.data.name); $('#email').html(res.data.email); }else{ $('#msg').html(res.data.msg); $(".jumbotron").addClass("d-none"); $("#msg").removeClass("d-none"); } $("#search").html('Search By Ajax'); } }); }); });</script>

Don’t worry i have already added the jQuery ajax code to get data from database in laravel on blade views.

So, you can add the following php and html form code into ajax-get-data-form.blade.php:<!DOCTYPE html><html><head> <title>How to Retrieve Data From Database using Ajax in Laravel 8</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script></head><body><div class="container mt-4"> <div class="card"> <div class="card-header text-center font-weight-bold"> <h2>Laravel 8 Ajax Get Data From Database</h2> </div> <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">Search Term</label> <input type="text" name="query" id="query" class="form-control" placeholder="Search by email and name"> </div> <button type="submit" class="btn btn-primary" id="search">Search By Ajax</button> <br> <div class="jumbotron d-none mt-2"> <span>Id :- </span><b id="id"></b><br> <span>Name :- </span><b id="name"></b><br> <span>Email :- </span><b id="email"></b><br> </div> <span id="msg"></span> </div> </div></div><script> $(document).ready(function($){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('body').on('click', '#search', function () { var str = $("#query").val(); $("#search").html('Please Wait...'); // ajax $.ajax({ type:"POST", url: "{{url('get-data-from-db')}}", data: { str: str }, dataType: 'json', success: function(res){ if(res.success == true){ $(".jumbotron").removeClass("d-none"); $("#msg").addClass("d-none"); $('#id').html(res.data.id); $('#name').html(res.data.name); $('#email').html(res.data.email); }else{ $('#msg').html(res.data.msg); $(".jumbotron").addClass("d-none"); $("#msg").removeClass("d-none"); } $("#search").html('Search By Ajax'); } }); }); });</script></body></html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for how to retrieve data from database using ajax in laravel application:

php artisan serve

Step 8 – Run Laravel 8 Ajax Get Data From Database App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/ajax-get-data-form

Last updated