
- 35 Views
Connecting Laravel with React Frontend Seamlessly
Integrating a Laravel backend with a React frontend is a common approach for building modern web applications. Laravel handles the server-side logic, database interactions, and API endpoints, while React provides a dynamic and responsive user interface. In this post, we explore a step-by-step approach to connect Laravel with React, including setting up CORS, building RESTful APIs, fetching data from React, handling authentication, and ensuring smooth communication between the two frameworks.
Setting Up Laravel API
Start by creating a Laravel project and defining your API endpoints. Use `api.php` for routes and controllers to handle CRUD operations. Make sure your API returns JSON responses for seamless integration with React.
1Route::get('/posts', [PostController::class, 'index']);
2Route::post('/posts', [PostController::class, 'store']);Tips for Laravel API Setup:
- Use resource controllers for standard CRUD endpoints
- Return JSON consistently using response()->json()
- Protect sensitive endpoints with authentication middleware
Handling CORS
Cross-Origin Resource Sharing (CORS) must be configured to allow React (running on a different port) to communicate with Laravel. Laravel includes a built-in CORS middleware that can be configured in `config/cors.php`.
1'paths' => ['api/*'],
2'allowed_methods' => ['*'],
3'allowed_origins' => ['http://localhost:3000'],
4'allowed_headers' => ['*'],CORS Tips:
- Allow React frontend origin in CORS settings
- Use wildcard '*' only for development
- Ensure proper headers for authorization requests
Fetching Data in React
Use the `fetch` API or libraries like Axios to request data from your Laravel API. React’s `useEffect` hook is perfect for fetching data when a component mounts, and `useState` can store the response for rendering.
1import { useState, useEffect } from 'react';
2import axios from 'axios';
3
4function Posts() {
5 const [posts, setPosts] = useState([]);
6 useEffect(() => {
7 axios.get('http://localhost:8000/api/posts')
8 .then(res => setPosts(res.data))
9 .catch(err => console.error(err));
10 }, []);
11
12 return <div>{posts.map(post => <div key={post.id}>{post.title}</div>)}</div>;
13}Fetching Data Tips:
- Use Axios for cleaner syntax and interceptors
- Handle loading and error states for better UX
- Keep API base URL in environment variables
Handling Form Submission
When sending data from React to Laravel, ensure proper request headers and JSON formatting. Use Axios or fetch to POST data, and validate it in Laravel controllers.
1axios.post('http://localhost:8000/api/posts', {
2 title: 'New Post',
3 content: 'Post content here'
4})
5.then(res => console.log(res.data))
6.catch(err => console.error(err));Form Submission Tips:
- Validate all input on the backend
- Return clear JSON responses with status codes
- Handle success and error messages gracefully in React
Authentication Between React and Laravel
Use Laravel Sanctum for token-based authentication. The frontend sends login credentials to Laravel, receives a token, and includes it in subsequent API requests. This ensures secure access to protected endpoints.
1axios.post('http://localhost:8000/api/login', { email, password })
2.then(res => {
3 localStorage.setItem('token', res.data.token);
4});
5
6axios.get('http://localhost:8000/api/posts', {
7 headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
8});Authentication Tips:
- Store tokens securely, e.g., localStorage or cookies
- Use Authorization headers for protected endpoints
- Implement logout by clearing the token
Real-World Example: Posts Management
By combining Laravel API endpoints with React frontend, we can build a full CRUD application. React handles user interactions like adding, editing, and deleting posts, while Laravel manages database storage, validation, and security.
1// React fetches posts
2useEffect(() => {
3 axios.get('/api/posts').then(res => setPosts(res.data));
4}, []);
5
6// Laravel PostController handles CRUD
7public function store(Request $request) {
8 $validated = $request->validate(['title' => 'required','content'=>'required']);
9 return Post::create($validated);
10}Best Practices:
- Keep frontend and backend loosely coupled
- Use RESTful conventions for API endpoints
- Handle errors gracefully on both sides
- Use environment variables for API URLs
Conclusion
Connecting Laravel with React combines the power of a robust backend with a dynamic frontend. By setting up APIs, configuring CORS, handling authentication, and managing data fetching properly, developers can create seamless and responsive applications. This approach improves maintainability, scalability, and user experience.
Key Takeaways:
- Use RESTful APIs for communication between React and Laravel
- Secure endpoints with authentication and CORS
- Fetch and handle data efficiently in React
- Keep frontend and backend modular for scalability
References
Resources for learning more about Laravel-React integration:




