How to use React Router with Laravel? How to use React Router with Laravel? laravel laravel

How to use React Router with Laravel?


Create a route that maps everything to one controller, like so:

Route::get('/{path?}', [    'uses' => 'ReactController@show',    'as' => 'react',    'where' => ['path' => '.*']]);

Then in your controller, just show the HTML page that contains the react root document:

class ReactController extends Controller {    public function show () {        return view('react');    }}

Then do everything as normal with react router. Seems to work well for me.


Update for Laravel 5.5If your controller only returns a view (like in the example above), you can replace all of the above code with this in your routes file:

Route::view('/{path?}', 'path.to.view')     ->where('path', '.*')     ->name('react');


Based on Jake Taylor answer (which is correct, by the way) : it has a little mistake, is missing a quotation mark after '/{path?}' , just the last one.

Also, if you don't need to use a Controller and just redirect back to your view, you can use it like this:

Route::get( '/{path?}', function(){    return view( 'view' );} )->where('path', '.*');

Note:Just make sure to add this Route at the end of all of your routes in the routes file ( web.php for Laravel 5.4 ), so every existing valid route you have may be catched before reaching this last one.


This seems works for me

For any react routes

Route::get('{reactRoutes}', function () {    return view('welcome'); // your start view})->where('reactRoutes', '^((?!api).)*$'); // except 'api' word

For laravel routes

Route::get('api/whatever/1', function() {    return [        'one' => 'two',        'first' => 'second'    ];});Route::get('api/something/2', function() {    return [        'hello' => 'good bye',        'dog' => 'cat'    ];});