Phillip Zoghbi
Phillip Zoghbi

Reputation: 610

React Fetch API in Laravel application

I've seen this not-so-perfect solution where we're supposed to place a universal view route and then route everything from react-router like so:

Route::view('/{any}', 'layouts.app')->where('any', '.*');

or

Route::view('/{any?}', 'layouts.app');

But the big issue here is when I'm fetching data to react from within my laravel application, for example: /posts, react-router will try to resolve /posts, but laravel will match it with /{any?}, and the fetch call will respond with a view.

Is there a way to make apiResource calls like described, and if so, how?

Upvotes: 1

Views: 680

Answers (1)

Phillip Zoghbi
Phillip Zoghbi

Reputation: 610

Name your API routes with the 'api' prefix 'api/posts' (for example).
Then let your react router do the routing for the application using one universal route:

Route::view('/{any?}', 'layouts.app');

This route comes after your API routes so that your API routes don't get matched with {'/any?'} parameter. (Very important!)

Then, you can have something like this in your react app:

<Routes>
    <Route path="/posts" element={<Posts/>} />
</Routes>

Upvotes: 1

Related Questions