段未移位/无法在Controller中获取正确的参数 [英] Segments are not getting shifted / Cannot get correct arguments in Controller

查看:111
本文介绍了段未移位/无法在Controller中获取正确的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为现有的Laravel项目实现简单的本地化.

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

基于以下教程实现本地化:
https://laraveldaily.com/multi-language-routes-and-locales-with-auth/

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

测试

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

结果:poll_id: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');
});

中间件/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保持不变.

PollsController@view remained unchanged.

现在,当我打开以下网址时( http://domain.name/en/poll/1 ),结果是:

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

结果:poll_id:

RESULT: poll_id: en

问题

是否有一种方法可以忽略'prefix'=>"{locale}"控制器中的参数或获取参数发生了某种变化,以便在控制器中我仍然得到 poll_id = 1 ,而不是 locale = en ?

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.最简单的解决方法是通过以下方式向PollsController @ view添加另一个参数,但是它闻起来不好,然后我需要向所有函数添加语言环境参数,尽管我在那里没有使用它:

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

推荐答案

在您的中间件中,您可以告诉Route实例忘记该route参数,这样它就不会尝试将其传递给route操作:

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

这篇关于段未移位/无法在Controller中获取正确的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆