Laravel 10 How To Get Data by Ajax Request Tutorial

Reading Time: 6 minutes
317 Views

Dynamic data retrieval is an important part of creating interactive and responsive user experiences in the world of modern web development. Laravel 10, known for its flexibility and resilience, provides a simple solution to accomplishing this via AJAX calls. This tutorial will guide you through the process of collecting data via AJAX queries in Laravel 10.

We begin the journey by recognising the relevance of real-time data retrieval and why it is critical for today’s web applications.

Read More: Laravel 10 RESTful APIs with JWT Authentication Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

How To Generate Fake Data in Laravel?

To generate fake data in a very easier way, you can use the concept of Factory.

Once you install laravel setup, you should see these files –

  • User.php a model file inside /app/Models folder.
  • UserFactory.php a factory file inside /database/factories folder.

You can use concept of factory to seed dummy data to this application.

But first you need to migrate your application’s migration to create users table into your database.

Go to tinker shell,

$ php artisan tinker

It will open tinker shell to execute commands. Copy and paste this command and execute to create test data.

>>> User::factory()->count(100)->create()

It will generate 100 fake rows of users into table.

Tinker shell,

Next,

Read More: How to Get Request Parameters in Laravel 10 Tutorial

Database table,

Next,

Setup Data Controller

You need to create a controller file,

$ php artisan make:controller UserController

It will create a file UserController.php inside /app/Http/Controllers folder.

Open file and write this complete code into it,

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::paginate(10);

        return view('users', compact('users'));
    }

    public function show($id)
    {
        $user = User::find($id);

        return response()->json($user);
    }
}

Create Blade Template File

Go to /resources/views folder and create a file with name users.blade.php

Open file and write this complete code into it,

<!DOCTYPE html>
<html>

<head>
    <title>Laravel 10 How To Get Data by Ajax Request Tutorial</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>

    <div class="container" style="margin-top: 10px;">

        <h3 style="text-align: center;">Laravel 10 How To Get Data by Ajax Request Tutorial</h3>

        <table class="table table-bordered data-table" style="margin-top: 30px;">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($users as $user)
                    <tr>
                        <td>{{ $user->id }}</td>
                        <td>{{ $user->name }}</td>
                        <td>{{ $user->email }}</td>
                        <td>
                            <a href="javascript:void(0)"
                                data-url="{{ route('users.show', $user->id) }}" class="btn btn-info show-user">Show</a>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
        {!! $users->withQueryString()->links('pagination::bootstrap-5') !!}

    </div>

    <!-- Modal -->

    <div class="modal fade" id="userShowModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">

                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">User details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                </div>

                <div class="modal-body">
                    <p><strong>ID:</strong> <span id="user-id"></span></p>
                    <p><strong>Name:</strong> <span id="user-name"></span></p>
                    <p><strong>Email:</strong> <span id="user-email"></span></p>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

</body>

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

        /*------------------------------------------
        --------------------------------------------
        When click user on Show Button
        --------------------------------------------
        --------------------------------------------*/
        $(document).on('click', '.show-user', function() {

            var userURL = $(this).data('url');

            $.ajax({
                url: userURL,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    $('#userShowModal').modal('show');
                    $('#user-id').text(data.id);
                    $('#user-name').text(data.name);
                    $('#user-email').text(data.email);
                }
            });

        });

    });

</script>

</html>

Add Route

Open web.php from /routes folder and add these route into it.

//...
use App\Http\Controllers\UserController;

//...

Route::get('users', [UserController::class, 'index']);
Route::get('users/{id}', [UserController::class, 'show'])->name('users.show');

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/users

Read More: How to Get Current Route Name in Laravel 10 Tutorial

List of all users

View single user data, click on Show button.

That’s it.

We hope this article helped you to Laravel 10 How To Get Data by Ajax Request Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more