Proper way to route vue/ajax requests in laravel?

2738 views php
-4

I'm new to laravel and making a web service that can function without javascript (if a user has it disabled or something.)

But it would be a better user experience to be able to perform certain actions without refreshing the whole page. I'd like to be able to say, send a form without reloading the page, or refresh notifications.

The options I can think of are:

1) Send the ajax to the same route as the pure html form, but with an extra variable and make my laravel respond with json when that variable is detected

2) Use the API route? Will this detect the currently logged in user?

3) Make new routes for everything ajax, even though they function the same as my current routes (aside from returning a view)

Also, does the CSRF token work multiple times in a row, or do I need to disable that to handle multiple ajax form posts in a row without page refreshes?

answered question

The proper way of doing it is to use API routes. As long as your middleware and Kernal.php is configured correctly it will detect the logged in user. Be sure your \App\Http\Middleware\EncryptCookies::class, and \Illuminate\Session\Middleware\StartSession::class, is in your api middlewareGroups

1 Answer

6

I recommend keeping the routes separate, both to prevent weird caching bugs and for your own sanity as the code changes over time.

Laravel is set up out of the box to let you define web routes in routes/web.php and api routes in routes/api.php. Routes defined in your api.php file will be available at /api/* by default. It's much easier to manage changing the application this way, rather than trying to make your controllers do both views and api responses.

With Laravel Passport, your API routes can detect the currently logged in user via the auth:api middleware when combined with adding the Laravel\Passport\Http\Middleware\CreateFreshApiToken to your web middleware group. https://laravel.com/docs/5.7/passport#consuming-your-api-with-javascript

An easy way to manage the duplicated controllers (one for web and one for api) is to put Api controllers in their own namespace, with php artisan make:controller Api/FooController. You can even set up your Api routes to look for controllers in this namespace by default by editing RouteServiceProvider.php.

posted this

Have an answer?

JD

Please login first before posting an answer.