Skip to content

Latest commit

 

History

History
77 lines (64 loc) · 2.18 KB

laravel-and-api-integration.md

File metadata and controls

77 lines (64 loc) · 2.18 KB
layout default
title Laravel and API Integration
description Laravel applications often involve more complex JavaScript interactions, particularly when building single-page applications or API-driven interfaces...
section JavaScript
section_slug javascript
parent JavaScript
nav_order 5
permalink /javascript/laravel-and-api-integration/

5.5 Laravel and API Integration

Laravel applications often involve more complex JavaScript interactions, particularly when building single-page applications or API-driven interfaces. We use modern fetch APIs for HTTP requests and handle authentication tokens properly.

// Laravel API integration
class ApiClient {
    constructor(baseUrl, token = null) {
        this.baseUrl = baseUrl;
        this.token = token;
    }

    async request(endpoint, options = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                ...options.headers
            },
            ...options
        };

        if (this.token) {
            config.headers.Authorization = `Bearer ${this.token}`;
        }

        // Add CSRF token for non-GET requests
        if (options.method && options.method !== 'GET') {
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
            if (csrfToken) {
                config.headers['X-CSRF-TOKEN'] = csrfToken;
            }
        }

        const response = await fetch(url, config);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return response.json();
    }

    get(endpoint) {
        return this.request(endpoint);
    }

    post(endpoint, data) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }
}

// Usage with Laravel
const api = new ApiClient('/api');

// Load user data
api.get('/user/profile')
    .then(user => updateProfileDisplay(user))
    .catch(error => showErrorMessage(error.message));