Table of Contents
2. Choose How to Serve React: SPA vs Inertia.js
Option A: Standalone React App (SPA)
Option B: Use Inertia.js (Recommended for Simplicity)
3. Build React Components Inside Laravel
4. Use Laravel as API React as Frontend (Decoupled)
Final Tips
Home PHP Framework Laravel How to integrate React with Laravel?

How to integrate React with Laravel?

Jul 30, 2025 am 04:05 AM
react laravel

Set up Laravel as an API backend by installing Laravel, configuring the database, creating API routes, and returning JSON from controllers, optionally using Laravel Sanctum for authentication. 2. Choose between a standalone React SPA served separately or using Inertia.js for tighter Laravel integration, with Inertia allowing React components to work within Laravel’s routing and session system. 3. When using Inertia, install the required packages, configure Vite, create a root React component, place React pages in resources/js/Pages/, and return Inertia responses from routes with data passed as props. 4. For a decoupled setup, run Laravel and React on separate domains, use Axios or Fetch to call Laravel APIs from React, and handle CORS and authentication properly. 5. Best practices include using Vite for faster builds, organizing React components by feature, formatting API responses with Laravel API resources, and testing CORS and authentication early. The choice between Inertia and a standalone React app depends on project complexity and team preferences, with Inertia simplifying full-stack integration and standalone SPAs offering greater frontend flexibility, both valid approaches for modern Laravel-React applications.

How to integrate React with Laravel?

Integrating React with Laravel allows you to build powerful, dynamic frontends while leveraging Laravel’s robust backend features like routing, authentication, and APIs. Here’s how to do it effectively in a modern Laravel project.

How to integrate React with Laravel?

1. Set Up Laravel and Create an API

First, make sure Laravel is set up to act as a backend API.

  • Install Laravel via Composer:

    How to integrate React with Laravel?
    composer create-project laravel/laravel your-project-name
  • Configure your .env file with database settings and run migrations:

    php artisan migrate
  • Create API routes in routes/api.php:

    How to integrate React with Laravel?
    Route::get('/posts', [PostController::class, 'index']);
  • Ensure your controllers return JSON (API resources or Eloquent collections):

    public function index()
    {
        return Post::all();
    }

Use Laravel Sanctum if you need authentication for your React frontend.


2. Choose How to Serve React: SPA vs Inertia.js

You have two main approaches:

Option A: Standalone React App (SPA)

  • Build React separately using Vite or Create React App.
  • Serve it from a different domain (e.g., http://localhost:3000) or as static files.
  • Configure Laravel to proxy API calls during development (optional).

✅ Best for large, complex frontends with many interactive components.

Inertia lets you use React components while staying within Laravel’s routing and session system.

  • Install Inertia:

    composer require inertiajs/inertia-laravel
  • Set up frontend scaffolding:

    npm install @inertiajs/react react react-dom @vitejs/plugin-react
  • Update vite.config.js:

    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import laravel from 'laravel-vite-plugin';
    
    export default defineConfig({
      plugins: [
        laravel({
          input: 'resources/js/app.jsx',
          refresh: true,
        }),
        react(),
      ],
    });
  • Create your root React component (resources/js/app.jsx):

    import { createRoot } from 'react-dom/client';
    import { createInertiaApp } from '@inertiajs/react';
    
    createInertiaApp({
      resolve: name => require(`./Pages/${name}`),
      setup({ el, App, props }) {
        createRoot(el).render(<App {...props} />);
      },
      title: title => `My App | ${title}`,
    });
  • Return Inertia responses from Laravel routes:

    use Inertia\Inertia;
    
    Route::get('/', function () {
        return Inertia::render('Welcome', ['message' => 'Hello from Laravel!']);
    });

✅ Great for full-stack apps where you want Laravel handling routing and React powering the UI.


3. Build React Components Inside Laravel

With Inertia or a bundled setup:

  • Place React components in resources/js/Pages/.

  • Example: resources/js/Pages/Posts/Index.jsx

    import { usePage } from '@inertiajs/react';
    
    export default function PostIndex({ posts }) {
      const { props } = usePage();
      return (
        <div>
          <h1>Posts</h1>
          {props.posts.map(post => (
            <div key={post.id}>{post.title}</div>
          ))}
        </div>
      );
    }
  • Pass data from Laravel controller:

    return Inertia::render('Posts/Index', [
        'posts' => Post::all()
    ]);

? For dynamic data (e.g., search, pagination), use Inertia visits or Axios to hit Laravel API routes.


4. Use Laravel as API React as Frontend (Decoupled)

If you prefer a fully separate frontend:

  • Keep Laravel running on api.yourapp.test (backend only).

  • Build React app (using Vite, Next.js, etc.) on localhost:3000.

  • Call Laravel APIs via Axios or Fetch:

    useEffect(() => {
      axios.get('http://api.yourapp.test/api/posts')
        .then(res => setPosts(res.data))
        .catch(err => console.error(err));
    }, []);
  • Handle CORS: Install fruitcake/laravel-cors or use Laravel Sanctum’s SPA features.

    composer require fruitcake/laravel-cors

⚠️ Remember to manage authentication (Sanctum/Socialite) and CSRF if not stateless.


Final Tips

  • Use Vite over Webpack (faster builds).
  • Keep React components organized by page or feature.
  • Use Laravel API resources to format JSON output cleanly.
  • Test CORS and authentication early.

Basically, you can either tightly couple React via Inertia or keep it separate as a frontend SPA. Inertia reduces complexity and keeps you in the Laravel ecosystem, while a standalone React app gives more frontend flexibility. Choose based on your team and project needs.

The above is the detailed content of How to integrate React with Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

RimWorld Odyssey How to Fish
1 months ago By Jack chen
Can I have two Alipay accounts?
1 months ago By 下次还敢
Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1506
276
How to implement a referral system in Laravel? How to implement a referral system in Laravel? Aug 02, 2025 am 06:55 AM

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

How to run a Laravel project? How to run a Laravel project? Jul 28, 2025 am 04:28 AM

CheckPHP>=8.1,Composer,andwebserver;2.Cloneorcreateprojectandruncomposerinstall;3.Copy.env.exampleto.envandrunphpartisankey:generate;4.Setdatabasecredentialsin.envandrunphpartisanmigrate--seed;5.Startserverwithphpartisanserve;6.Optionallyrunnpmins

How to seed a database in Laravel? How to seed a database in Laravel? Jul 28, 2025 am 04:23 AM

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4

How to build a REST API with Laravel? How to build a REST API with Laravel? Jul 30, 2025 am 03:41 AM

Create a new Laravel project and start the service; 2. Generate the model, migration and controller and run the migration; 3. Define the RESTful route in routes/api.php; 4. Implement the addition, deletion, modification and query method in PostController and return the JSON response; 5. Use Postman or curl to test the API function; 6. Optionally add API authentication through Sanctum; finally obtain a clear structure, complete and extensible LaravelRESTAPI, suitable for practical applications.

How to implement feature flags in a Laravel app? How to implement feature flags in a Laravel app? Jul 30, 2025 am 01:45 AM

Chooseafeatureflagstrategysuchasconfig-based,database-driven,orthird-partytoolslikeFlagsmith.2.Setupadatabase-drivensystembycreatingamigrationforafeature_flagstablewithname,enabled,andrulesfields,thenrunthemigration.3.CreateaFeatureFlagmodelwithfilla

What is Eloquent ORM in Laravel? What is Eloquent ORM in Laravel? Jul 29, 2025 am 03:50 AM

EloquentORM is Laravel's built-in object relational mapping system. It operates the database through PHP syntax instead of native SQL, making the code more concise and easy to maintain; 1. Each data table corresponds to a model class, and each record exists as a model instance; 2. Adopt active record mode, and the model instance can be saved or updated by itself; 3. Support batch assignment, and the $fillable attribute needs to be defined in the model to ensure security; 4. Provide strong relationship support, such as one-to-one, one-to-many, many-to-many, etc., and you can access the associated data through method calls; 5. Integrated query constructor, where, orderBy and other methods can be called chained to build queries; 6. Support accessors and modifiers, which can format the number when obtaining or setting attributes.

What are Repository Contracts in Laravel? What are Repository Contracts in Laravel? Aug 03, 2025 am 12:10 AM

The Repository pattern is a design pattern used to decouple business logic from data access logic. 1. It defines data access methods through interfaces (Contract); 2. The specific operations are implemented by the Repository class; 3. The controller uses the interface through dependency injection, and does not directly contact the data source; 4. Advantages include neat code, strong testability, easy maintenance and team collaboration; 5. Applicable to medium and large projects, small projects can use the model directly.

Using Form Requests for Validation in Laravel. Using Form Requests for Validation in Laravel. Jul 30, 2025 am 05:04 AM

Use FormRequests to extract complex form verification logic from the controller, improving code maintainability and reusability. 1. Creation method: Generate the request class through the Artisan command make:request; 2. Definition rules: Set field verification logic in the rules() method; 3. Controller use: directly receive requests with this class as a parameter, and Laravel automatically verify; 4. Authorization judgment: Control user permissions through the authorize() method; 5. Dynamic adjustment rules: dynamically return different verification rules according to the request content.

See all articles