我的项目是多语言的,所以在大多数 route 我添加了参数“locale”。但后者我不需要将“locale”参数传递给我的 Controller 。我尝试使用 删除此参数忘记参数() 方法,但是当我使用此方法时,出现错误“ Route not bound ”。
所以我做错了什么。
如何从所有 route 删除“语言环境”?
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')
我有以下错误:
Call to a member function is() on null
谢谢你。
最佳答案
尝试忘记 Controller 构造函数中内联中间件中的参数。实际上,我会使用一个基本 Controller : 1,获取路由值; 2、设置为一个 protected 属性,这样继承的 Controller 就可以访问该值; 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);
}
}
关于Laravel - 忘记参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696665/