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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 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));