Reputation: 975
I'm building a multi languages site using Laravel 5.
I knew that in Laravel, I can define prefix
for route like:
http://domain/en/users/1
http://domain/en/shop/1
And in Middleware, I can get the segment of url path to detect the language and set locale of current Request.
But I can't find anyway to add lang parameter in default for route like folowings:
http://domain/users/1?lang=en
http://domain/shop/1?lang=en
Or are there anyways to hook into route function of Framework to append default parameter ?lang=ja
into all route when I call ?
(ja is current locale of application which was set in middleware before )
Thanks !
Upvotes: 0
Views: 3684
Reputation: 1944
You can create a middleware that sets up a default 'lang' query parameter if the request doesn't have one. It will work for all the requests to your app, so you can get the lang parameter in every route handler.
Create a middleware LangFilter in the console (while in the project directory) :
php artisan make:middleware LangFilter
Then open up ./app/Http/Kernel.php
and add :
\App\Http\Middleware\LangFilter::class
to the $middleware
array. Now open up the middleware you created, i.e ./app/Http/Middleware/LangFilter.php
and add the checking and setting code :
<?php
namespace App\Http\Middleware;
use Closure;
class LangFilter
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Checks for lang in the parameters.
if($request->input('lang') == null) {
// Adds the default one since it doesn't have one.
$request->merge(array('lang' => 'en'));
}
return $next($request);
}
}
If you want to have this kind of filtering for just a subset of all the routes you have, you need to register the middleware differently in Kernel.php.
UPDATE
For making a helper that generates routes with current locale :
Open up helpers.php, and add this code to add the helper :
<?php
function locale_route($name, $parameters = [], $absolute = true) {
return route($name, array_merge($parameters, [
'lang' => App::getLocale()
]), $absolute);
}
?>
Add the helpers file to composer autoload in composer.json:
"autoload" : {
"files" : [
"app/Support/helpers.php"
]
}
Now run in the console :
composer dumpautoload
Now you can call locale_route
with the same parameters you give to route
to create urls that has the current locale added in query params.
Upvotes: 1
Reputation: 3257
I hope this is what you are looking for. Generating a route with a query string parameter
Upvotes: 0