Segments are not getting shifted / Cannot get correct arguments in Controller

↘锁芯ラ 提交于 2021-01-29 17:11:57

问题


I am trying to implement a simple localization for an existing Laravel project.

Implementing Localization based on the following tutorial:
https://laraveldaily.com/multi-language-routes-and-locales-with-auth/

Here is the simplified code before localization implementation:

web.php

Route::get('/poll/{poll_id}', 'App\Http\Controllers\PollsController@view');

PollsController@view

public function view($poll_id){
    echo "poll_id: ".$poll_id;
}

TEST

URL: http://domain.name/poll/1

RESULT: poll_id: 1

Here are the simplified changes required for localization and the result I get:

web.php

Route::group(['prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}'], 'middleware' => 'setlocale'], function() {    
    Route::get('/poll/{poll_id}', 'App\Http\Controllers\PollsController@view');
});

Middleware/SetLocale

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next){
        app()->setLocale($request->segment(1));
        return $next($request);
    }
}

PollsController@view remained unchanged.

Now, when I open the following URL (http://domain.name/en/poll/1), the result is:

RESULT: poll_id: en

QUESTION

Is there a way to ignore "'prefix' => '{locale}'" in controller or get arguments somehow shifted so that in the controller I still get poll_id=1, not locale=en?

PS. The easiest fix would be to add another argument to PollsController@view in the following way, but it does not smell well and then I would need to add locale argument to all functions, although I do not use it there:

public function view($locale, $poll_id){
    echo "poll_id: ".$poll_id;
}

回答1:


In your middleware you can tell the Route instance to forget that route parameter so it won't try to pass it to route actions:

public function handle($request, $next)
{
    app()->setLocale($request->route('locale'));

    // forget the 'locale' parameter
    $request->route()->forgetParameter('locale');

    return $next($request);
}


来源:https://stackoverflow.com/questions/65594630/segments-are-not-getting-shifted-cannot-get-correct-arguments-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!