Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

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

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}', 'AppHttpControllersPollsController@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}', 'AppHttpControllersPollsController@view');
});

Middleware/SetLocale

namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...