Laravel GET request


To make a GET request to a Laravel API using JavaScript's Fetch API, you will typically follow these steps:

  1. Set Up the Laravel API: Define the route and controller method to handle the GET request.
  2. Create the Frontend: Use JavaScript's Fetch API to make the GET request to the Laravel API.
  3. Handle the Response: Process the response from the API and update the UI as needed.

Step-by-Step Guide

1. Set Up the Laravel API

First, ensure you have a Laravel API set up. Below is an example for fetching users from a database.

Define the Route:

In routes/api.php, define a route for fetching users:

use App\Http\Controllers\UserController; Route::get('/users', [UserController::class, 'index']);

Create the Controller Method:

In UserController.php, implement the index method to return users:

namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function index() { $users = User::all(); // Fetch all users return response()->json($users); // Return users as JSON } }

2. Create the Frontend with JavaScript Fetch API

You can use the Fetch API to make a GET request from your frontend code (HTML/JavaScript). Here’s a simple example:

HTML Structure:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fetch Users</title> </head> <body> <h1>Users List</h1> <ul id="user-list"></ul> <script src="app.js"></script> <!-- Link to your JavaScript file --> </body> </html>

JavaScript Fetch Request:

In a file named app.js, you can write the Fetch API code to get the users:

document.addEventListener('DOMContentLoaded', () => { // Function to fetch users from the API function fetchUsers() { fetch('http://your-app.test/api/users') // Replace with your API URL .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); // Parse JSON response }) .then(data => { const userList = document.getElementById('user-list'); userList.innerHTML = ''; // Clear existing list // Populate the user list data.forEach(user => { const listItem = document.createElement('li'); listItem.textContent = `${user.name} (${user.email})`; // Customize as needed userList.appendChild(listItem); }); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); } fetchUsers(); // Call the function to fetch users });

3. Handling CORS (Cross-Origin Resource Sharing)

If your Laravel API and frontend are running on different origins (different domains or ports), you might encounter CORS issues. To enable CORS in Laravel, you can use the Laravel CORS package.

You can install it via Composer if it isn't already included in your project:

composer require fruitcake/laravel-cors

After installing, configure the CORS settings in config/cors.php to allow requests from your frontend's origin.

Summary

In this guide, you learned how to:

  • Set up a simple Laravel API to return user data.
  • Use the Fetch API in JavaScript to make a GET request to that API.
  • Handle the response and dynamically update the HTML to display the user data.

This process allows you to integrate your Laravel backend with a frontend application, enabling dynamic data fetching and display.