Skip to content
Manuele J Sarfatti edited this page Oct 29, 2019 · 10 revisions

Create React App Laravel

Requirements

A working Laravel 6 project, preferably pristine.

Installation

  1. In your Laravel folder install the necessary Create React App files and scripts, by running exactly:
npx [email protected] . --scripts-version [email protected] --template laravel
  1. Now register the route that will serve the React app by appending to routes/web.php (this example assumes that your app will be reachable at /app, but feel free to modify it to your convenience):
Route::get('/app{any?}', function () {
    return view('app');
})->where('any', '.*')->name('app');
  1. Build the app a first time to generate the necessary blade view:
yarn build
  1. Happy hacking!

How Create React App Laravel works

TL;DR Except for the installation instructions and the build process (see note below), everything else works exactly the same as in Create React App. yarn start will open http://localhost:3000/ in a browser tab, yarn build will build the app, etc.
You can refer to the official docs for all your needs.

Folder structure

[L] denotes a Laravel-made folder or file
[R] denotes a Create React App Laravel-made folder or file

app [L]
bootstrap [L]
config [L]
database [L]
node_modules [R]
public [L/R] // created by Laravel, it's now the 'build' folder of CRAL
resources
  |- js [L] // safe to delete if not used
  |- lang [L]
  |- react-app [R] // this is where your React app resides
       |- public [R]
       |- src [R]
  |- sass [L] // safe to delete if not used
  |- views [L+R]
       |- app.blade.php [R] // generated by 'yarn build'
       |- ... [L]
routes [L]
storage [L]
tests [L]
vendor [L]
.gitignore [L+R] // CRAL will append certain rules to your existing .gitignore file
artisan [L]
composer.json [L]
composer.lock [L]
package.json [R]
phpunit.xml [L]
README.md [R]
README.old.md [L] // CRAL backups your eventually existing README here
server.php [L]
webpack.mix.js [L]
yarn.lock [R]

Explanation

The React app resides in the folder resources/react-app. Here you will find our usual public and src folders, just like in Create React App (standard).

Here is our only gotcha though: the folder resources/react-app/public is sourced by yarn build, and then copied into Laravel's public folder. Another way of seeing it is to think of Laravel's public folder as the location that would have been Create React App's build folder.

This is the reason why when you install Create React App Laravel for the first time you will find Laravel's default .htaccess and index.php files in CRAL's public folder.

There is only one exception to this: the resources/react-app/public/index.html file. Even though the extension is .html you should treat it as a blade PHP file. Once the <style> and <script> tags are injected into index.html this file is renamed and moved to resources/views/app.blade.php.

⚠️ PLEASE NOTE ⚠️

Running yarn build wipes out Laravel's public folder every time, and rebuilds it sourcing resources/react-app/public. If you want files to persist (eg. a custom .htaccess configuration) that’s where you should place them.

If you have CI in place you may even want to gitignore Laravel's public folder.

Developing

Eventually, you will probably want to serve the front-end React app from the same host as the backend Laravel implementation. For example, a production setup might look like this after the app is deployed:

/             - static server returns index.html with React app
/todos        - static server returns index.html with React app
/api/todos    - server handles any /api/* requests using the backend implementation

In your local environment you may already have a virtual host set up to serve your Laravel app, such as my-project.test, with your API reachable at http://my-project.test/api.
By serving the React app from that same virtual host you would get two benefits:

  1. Cookies are shared (it can be useful for example if your React app is only reachable after logging in, and you manage authentication using Laravel sessions)
  2. You can write API requests just as if you were in production: fetch('/api/todos')

Here's how to set this up in your local environment:

  1. Run yarn add http-proxy-middleware --dev
  2. Modify your package.json > scripts > start as follows:
"start": "HOST=my-project.test react-scripts start",
  1. Create the file resources/react-app/src/setupProxy.js with the following content:
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    proxy({
      target: 'http://my-project.test',
      changeOrigin: true
    })
  );
};

From now on when you run yarn start the webpack development server will be started on http://my-project.test:3000. Any fetch('/api/*') request will be transparently redirected to your Laravel installation.

Please note: the webpack development server serves a static HTML file as found in resources/react-app/public/index.html. It does NOT run requests through Laravel (this is the reason why, for example, the <title> reads literally {{ config('app.name', 'Laravel') }}.

FAQ

Why are you specifying a semver with a Release Candidate mark? Is it not safe to use in production? Yes, it is safe. But we make use of a feature (--template) that will be released with [email protected], hence the rc.x mark.

Can I add a React app in an existing Laravel project?
Yes you can. But know this:

  1. create-react-app-laravel lives in the resources/react-app folder, so if you already have such folder make sure you rename it to something else. It will also generate a resources/views/app.blade.php file, so make sure you are not using such a file already.
  2. Every time you yarn build the app the entire content Laravel's public folder will be wiped out, and rebuilt sourcing the contents of resources/react-app/src/public. So make sure you back up any file in public you want to preserve, and after installing Create React App Laravel you move those files to resources/react-app/src/public.

Does it work with Laravel 5.x? I don't know, but I would be forever grateful if you could give it a spin and tell me! 🙏

Where is the build folder? If you are used to Creat React App you are probably expecting it to be in resources/react-app. Since we are working with Laravel, though, and since Laravel's web root is the folder public, that's where you will find your build. With one difference: resources/react-app/public/index.html is compiled and placed in resources/views/app.blade.php.