Certainly! Here’s a clear solution to your question about making non-Inertia API requests from a React component in an Inertia.js/Laravel app.
1. Use Axios or Fetch for API Requests
You can use either axios or the native fetch API to make requests to your Laravel backend. Axios is commonly used because of its simplicity and automatic CSRF token handling (with some setup).
2. API vs Web Routes
- If your React component is making requests that don’t require a full page reload or Inertia navigation, you can use either API routes (
routes/api.php) or web routes (routes/web.php). - If you use API routes, authentication is usually handled via Laravel Sanctum or Passport.
- If you use web routes, you need to handle CSRF tokens for POST/PUT/DELETE requests.
3. CSRF Token Handling
- For web routes, you need to include the CSRF token in your requests.
- Laravel includes the CSRF token as a meta tag in your HTML by default:
<meta name="csrf-token" content="{{ csrf_token() }}">
- You can grab this token in your JavaScript and include it in your requests.
4. Example: Using Axios
First, install axios if you haven’t:
npm install axios
Then, set up axios to include the CSRF token by default:
import axios from 'axios';
// Get CSRF token from meta tag
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
axios.defaults.headers.common['X-CSRF-TOKEN'] = token;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Now, you can make a POST request to create a company:
axios.post('/companies', {
name: 'New Company',
// ...other fields
})
.then(response => {
// Handle success, e.g., update your select field
})
.catch(error => {
// Handle error
});
5. Example: Using Fetch
If you prefer fetch:
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch('/companies', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token,
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({
name: 'New Company',
// ...other fields
}),
})
.then(response => response.json())
.then(data => {
// Handle success
})
.catch(error => {
// Handle error
});
6. Do You Need Sanctum?
- If you use API routes (
routes/api.php), you generally need Sanctum for authentication. - If you use web routes, and your user is already authenticated via Laravel session, you don’t need Sanctum—just make sure to include the CSRF token.
Summary
- Use axios or fetch for non-Inertia requests.
- For web routes, include the CSRF token.
- For API routes, use Sanctum for authentication.
- Axios is not pre-installed, but you can easily install and configure it as shown above.
Let me know if you need a more specific example or further clarification!