我需要在我的项目中实现本地化。 我添加了一个带前缀的组。
Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale'
], function () {
...
Route::resource('projects', 'ProjectsController');
...
})
中间件setlocale
<?php
namespace App\Http\Middleware;
use Closure;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
app()->setLocale($request->segment(1));
return $next($request);
}
}
路由器列表
+--------+----------------------------------------+--------------------------------------------+---------------------------+----------------------------------------------------------------------------+---------------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------------------------------------+--------------------------------------------+---------------------------+----------------------------------------------------------------------------+---------------------+
| | POST | {locale}/projects | projects.store | App\Http\Controllers\ProjectsController@store | web,setlocale,auth |
| | GET|HEAD | {locale}/projects | projects.index | App\Http\Controllers\ProjectsController@index | web,setlocale,auth |
| | GET|HEAD | {locale}/projects/create | projects.create | App\Http\Controllers\ProjectsController@create | web,setlocale,auth |
| | DELETE | {locale}/projects/{project} | projects.destroy | App\Http\Controllers\ProjectsController@destroy | web,setlocale,auth |
| | PUT|PATCH | {locale}/projects/{project} | projects.update | App\Http\Controllers\ProjectsController@update | web,setlocale,auth |
| | GET|HEAD | {locale}/projects/{project} | projects.show | App\Http\Controllers\ProjectsController@show | web,setlocale,auth |
| | GET|HEAD | {locale}/projects/{project}/edit | projects.edit | App\Http\Controllers\ProjectsController@edit | web,setlocale,auth |
+--------+----------------------------------------+--------------------------------------------+---------------------------+----------------------------------------------------------------------------+---------------------+
一切正常。但是有一个问题。 当我打开路线时:
我遇到错误
参数1传递给App \ Http \ Controllers \ ProjectsController :: show() 必须是App \ Project的实例,给定字符串
我将$ locale添加到我的show方法中,并且有效
public function show($locale, Project $project, Request $request)
{
}
如何摆脱方法中的参数,以免将其插入到各处。
我尝试了这种方法,但它不起作用:
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function callAction($method, $parameters)
{
unset($parameters['locale']);
return parent::callAction($method, $parameters); // TODO: Change the autogenerated stub
}
}
错误
参数1传递给App \ Http \ Controllers \ ProjectsController :: show() 必须是App \ Project的实例, 照亮\ Http \已发出请求
答案 0 :(得分:2)
在设置区域设置后,将其添加到您的中间件中:
$request->route()->forgetParameter('locale');
您现在可以从$locale
方法或任何其他使用show()
的方法中删除$locale
。