Routes using annotations - passing custom variables and translation

1.1k views Asked by At

Using routes.php it's quite easy to create paths for different languages using prefixes, for example we can create for about page routes about and pl/o-nas urls to the same route using:

if (\Request::segment(1) =='pl') {
    $prefix ='pl';
    \App::setLocale('pl');
}
else{
    $prefix ='';
    \App::setLocale('en');
}

Route::group(
    array('prefix' => $prefix,
    function () {
        Route::any('/'.trans('routes.about'), 'Controller@action'); 
    }
);

But as we know Laravel 5 by default uses annotation. Is it possible to achieve the same using annotations? At the moment there are not many information about using annotations in Laravel 5.

You can first add to RouteServiceProver into before method the similar code:

if (\Request::segment(1) =='en') {
    $routePrefix ='';
    $this->app->setLocale('en');
}
else{
    $routePrefix ='pl';
    $this->app->setLocale('pl');
}

but how we can use this prefix and translation in annotations itself and how to use trans function here? It should be something like this but it obviously won't work because you cannot simply put function into annotation and I don't know if there is any way to add prefix here.

/**
 * @Get("/trans('routes.about')")
 * @prefix: {$prefix}
 */
public function about()
{
   return "about page";
}
1

There are 1 answers

3
Laurence On

Something like this should work:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;

class LangDetection implements Middleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->segment(1) =='en') {
              $this->app->setLocale('en');
        }
        else{
              $this->app->setLocale('pl');
        }

        return $next($request);
    }

}

Then to make sure that is run on every call - put it into the application middleware stack (app/Providers/AppServiceProvider.php):

protected $stack = [
    'App\Http\Middleware\LangDetection',
    'Illuminate\Cookie\Middleware\Guard',
    'Illuminate\Cookie\Middleware\Queue',
    'Illuminate\Session\Middleware\Reader',
    'Illuminate\Session\Middleware\Writer',
];

Edit: alternatively you dont have to put it in the stack, you can leave it as a 'middleware filter' and just call it on specific routes - same as you already do for 'auth', 'csrf' etc