Friday, December 27, 2024
Google search engine
HomeLanguagesLaravel 10 Fetch Data using Ajax Tutorial Example

Laravel 10 Fetch Data using Ajax Tutorial Example

When you are making an app in Laravel app. Then you have to show some data on the page or modals without refreshing the page. At that time, you can display the data by using Jquery and Ajax in laravel app. That too without refreshing the entire page.

Laravel 10, 9, 8 fetch data using ajax. In this tutorial, we will show you how to retrieve or get data from database using ajax in laravel 10, 9, 8 app.

So, this tutorial will guide you on how to fetch or get data using ajax in laravel from controller and show it in views.

Fetch Records from MySQL with jQuery AJAX in Laravel 10

Follow the following steps to fetch/get and display records from MySQL db with jquery ajax laravel apps:

  • Step 1 – Install Laravel App
  • Step 2 – Connecting App to Database
  • Step 3 – Execute Database Migration Command
  • Step 4 – Add Routes
  • Step 5 – Create Controller and Method to Fetch Data
  • Step 6 – Create Blade Views
  • Step 7 – Start Development Server
  • Step 8 – Test This App

Step 1 – Install Laravel App

In this step, Execute the following command to install laravel app, so open terminal and execute the following command:

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

Step 2 – Connecting App to Database

Then, Visit laravel 8 app root directory, find .env file. After that, add database credential:

 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

Step 3 – Execute Database Migration Command

In this step, execute the following command to create tables into database:

php artisan migrate

Step 4 – Add Routes

In this step, open web.php file and add the following routes into it, which is placed inside routes directory:

use App\Http\Controllers\AjaxController;

Route::get('list', [AjaxController::class, 'index']);
Route::get('show-user', [AjaxController::class, 'show']);

Step 5 – Create Controller and Method to Fetch Data

In this step, execute the following command to create ajax controller:

php artisan make:controller AjaxController

After that, open this controller in any text editor and add the following code into it, which is located inside app/http/controllers directory:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;

use Redirect,Response;

use App\Models\User;
  
class AjaxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['users'] = User::orderBy('id','desc')->paginate(8);
  
        return view('list',$data);
    }
   
  
    public function show($id)
    {   
        $where = array('id' => $id);
        $user  = User::where($where)->first();

        return Response::json($user);
    }

}

Step 6 – Create Blade Views

In this step, create one blade view file named list.blade.php file. So, visit the resources/views directory and create list.blade.php file.

Then add the following code into the list.blade.php file:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>laravel 9 Get Data From Database using Ajax - Tutsmake.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

 <style>
   .container{
    padding: 0.5%;
   } 
</style>
</head>
<body>

<div class="container">
    <h2 style="margin-top: 12px;" class="alert alert-success">laravel 8 Get Data From Database Using Ajax</h2><br>
    <div class="row">
        <div class="col-12">
          <table class="table table-bordered" id="">
           <thead>
              <tr>
                 <th>Id</th>
                 <th>Name</th>
                 <th>Email</th>
                 <td colspan="2">Action</td>
              </tr>
           </thead>
           <tbody id="users-crud">
              @foreach($users as $u_info)
              <tr id="user_id_{{ $u_info->id }}">
                 <td>{{ $u_info->id  }}</td>
                 <td>{{ $u_info->name }}</td>
                 <td>{{ $u_info->email }}</td>
                 <td><a href="javascript:void(0)" id="show-user" data-id="{{ $u_info->id }}" class="btn btn-info">Show</a></td>
              </tr>
              @endforeach
           </tbody>
          </table>
          {{ $users->links() }}
       </div> 
    </div>
</div>

</body>
</html>

After that, create one modal for display data on it using ajax. So add the following code into list.blade.php file:

<div class="modal fade" id="ajax-modal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title" id="userShowModal"></h4>
        </div>
        <div class="modal-body">
            <form id="userForm" name="userForm" class="form-horizontal">
               <input type="hidden" name="user_id" id="user_id">
                <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">Name</label>
                    <div class="col-sm-12">
                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">Email</label>
                    <div class="col-sm-12">
                        <input type="email" class="form-control" id="email" name="email" placeholder="Enter Email" value="" required="">
                    </div>
                </div>
            </form>
        </div>
    </div>
  </div>
</div>

Now, add the following javascript code into list.blade.php file for display data on modals using ajax in laravel app:

<script>
  $(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

   /* When click show user */
    $('body').on('click', '#show-user', function () {
      var user_id = $(this).data('id');
      $.get('ajax-crud/' + user_id +'/edit', function (data) {
         $('#userShowModal').html("User Details");
          $('#ajax-modal').modal('show');
          $('#user_id').val(data.id);
          $('#name').val(data.name);
          $('#email').val(data.email);
      })
   });
  
  });
  
 
</script>

Step 7 – Run Development Server

In this step, execute the php artisan serve command on terminal to start development server:

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

Step 8 – Test This app

Now, open browser and hit the following url on it:

http://127.0.0.1:8000/list

Conclusion

Laravel 9, 8 fetch data using ajax tutorial, you have learned how to retrieve data from database using ajax in laravel 9, 8 app.

Recommended Laravel Tutorials

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

RELATED ARTICLES

Most Popular

Recent Comments