How to Use React with Laravel – Integrating Your Front-End with PHP Backend

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

React is a powerful JavaScript library for building user interfaces, while Laravel is a robust PHP framework for server-side applications. Integrating the two can deliver a dynamic and efficient full-stack web application. In this tutorial, we’ll guide you through integrating your React front-end with a Laravel PHP backend.

Prerequisites

  • Basic knowledge of PHP and JavaScript
  • Laravel and React environment setup
  • Composer and npm/Yarn installed

Step-by-Step Instructions

Step 1: Setting Up Laravel

composer create-project --prefer-dist laravel/laravel laravel-react-integration

Enter the project’s directory:

cd laravel-react-integration

Step 2: Setting Up React

Add React to your project using Laravel Mix:

npm install react react-dom
npm install laravel-mix@^6.0.6

Now configure webpack.mix.js:

const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
    .react()
    .sass('resources/sass/app.scss', 'public/css');

Step 3: Create React Components

Create a component in resources/js/components directory:

npm install -D babel-plugin-syntax-dynamic-import

Edit your resources/js/app.js to include the component:

import React from 'react';
import ReactDOM from 'react-dom';
function Example() {
    return (
        <div className="App">
            <h1>Hello, React!</h1>
        </div>
    );
}
if (document.getElementById('app')) {
    ReactDOM.render(<Example />, document.getElementById('app'));
}

Step 4: Integrating React with Laravel Routes

Create an endpoint in routes/web.php:

Route::view('/', 'app');

Create a view resources/views/app.blade.php and include the React component:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React with Laravel</title>
    <link rel="stylesheet" href="{{ mix('css/app.css') }}">
</head>
<body>
    <div id="app"></div>
    <script src="{{ mix('js/app.js') }}"></script>
</body>
</html>

Step 5: Connecting to the Backend Using API

Create an API route in routes/api.php and a corresponding controller:

Route::get('/data', 'ApiController@index');

In your React component, fetch data:

useEffect(() => {
    fetch('/api/data')
        .then(response => response.json())
        .then(data => {
            // Handle data
        });
}, []);

Step 6: Building and Running Your Application

Compile your JavaScript and styles using Laravel Mix:

npm run dev

Start your Laravel application:

php artisan serve

Conclusion

By combining the React front-end with Laravel back-end, you’ve set the stage for a highly interactive and powerful web application. Keep experimenting and refining the process as you scale your application.