António Quadrado
António Quadrado

Reputation: 1325

Laravel 5.3 How to avoid locale before prefix in api routes in multilanguage app?

I've built a multilanguage app in Laravel 5.3 and I have a bunch of api routes that return me some resources where the url is something like this http://app-domain.com/api/resource when I'm on my default language.

The problem presents itself when I'm not in the default language. When the app tries to call the api it sends a request to http://app-domain.com/locale/api/resource which returns nothing since it's not the correct path.

My implementation is very simple, just basic routing in my routes/api.php

Route::group([
    'prefix' => 'api'
  ],function() {
    Route::get('resource', 'ApiController@getResource')->name('get-resource');
});

Then I'm using jquery ajax object to call it

$.get( "api/resource", function( data ) {
  //run somecode
});

How can I address this problem and have my api routes resolving correctly no matter the language? Is there some params that I can set in the routes to prevent this? I've been looking in the documentation but found nothing relevant.

P.S.: I'm using Mcmanamara Laravel Localization

Upvotes: 1

Views: 665

Answers (1)

dparoli
dparoli

Reputation: 9161

IMHO for setting locale its better if you use a query-string: i.e.:

http://app-domain.com/api/resource?locale=en

For two, valid, reasons:

1) The locale in the querystring could also be non existing, so you can fallback to default locale.

2) Having a locale parameter in a route could conflict with other routes parameters generating a lot of confusion

Upvotes: 1

Related Questions