【问题标题】:Laravel - forgetParameterLaravel - 忘记参数
【发布时间】:2019-11-03 21:43:19
【问题描述】:

我的项目是多语言的,所以在大多数路线中我添加了参数“locale”。但后者我不需要将“语言环境”参数传递给我的控制器。我尝试使用 forgetParameter() 方法删除此参数,但是当我使用此方法时,出现错误“Route not bound”。

所以我做错了什么。

如何从所有路由中删除“语言环境”?

Laravel 5.8

我的路线文件。

Route::group(['prefix' => '{locale}','where' => ['locale' => '[a-zA-Z]{2}']], function() {

Auth::routes([app()->getLocale()]);
Route::get('/', 'HomeController@index')->name('mainPage');


Route::get('/user/{id}','UserController@showUser')->name('getUserProfile')->forgetParameter('locale');
Route::get('/user/{id}/edit','UserController@editUser')->name('editUserProfile')
    ->middleware('can:editUser,App\User,id')->forgetParameter('locale');
Route::patch('/user/{id}/edit','UserController@updateUser')->name('updateUserProfile')
    ->middleware('can:updateUser,App\User,id')->forgetParameter('locale');

});

这个问题不重复 - Laravel 5.4: How to DO NOT use route parameter in controller

该问题的解决方案不适用于我的情况。我的问题是为什么“forgotParamter()”会抛出错误?

另一个问题是,为什么我不能在中间件中使用这种结构:

$request->route()->forgetParameter('locale')

我有以下错误:

在 null 上调用成员函数 is()

谢谢。

【问题讨论】:

标签: laravel routes


【解决方案1】:

尝试忘记控制器构造函数中内联中间件中的参数。实际上,我会使用基本控制器: 1、获取路由值; 2、设置为受保护的属性,以便继承的控制器可以访问该值; 3、忘记参数。

<?php
// Localized/Controller.php
namespace App\Http\Controllers\Localized;

use App\Http\Controllers\Controller as ControllerBase;
use Illuminate\Http\Request;

class Controller extends ControllerBase
{
    protected string $currentLocale;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            // If you need to access this later on inherited controllers
            $this->currentLocale = $request->route('locale') ?? 'en';

            // Other operations, like setting the locale or check if lang is available, etc
 
            $request->route()->forgetParameter('locale');

            return $next($request);
        });
    }
}

<?php
// Localized/UserController.php
namespace App\Http\Controllers\Localized;

use Illuminate\Http\Request;

// Extends the our base controller instead of App\Http\Controllers\Controller
class UserController extends Controller 
{
    public function show(Request $request)
    {
        // No need of string $locale arg
        dd($this->currentLocale);
    }

}

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 2018-11-05
    • 1970-01-01
    • 2019-10-04
    • 2018-08-31
    • 2015-08-06
    • 2018-08-12
    • 2017-11-09
    • 2017-02-11
    相关资源
    最近更新 更多