[英]Laravel 5.4: Custom view for route-model-binding not finding the ID
正如我开始使用Laravel一样,这应该很简单:当我的路由模型绑定找不到给定的ID时,如何定义要渲染的自定义视图?
这是我的路线:
Route::get('/empresa/edit/{empresa}', 'EmpresaController@edit');
这是我的控制器的方法:
public function edit(Empresa $empresa)
{
if ((!isset($empresa)) || ($empresa == null)):
//I get that this won't work...
return 'Empresa não encontrada';
endif;
return view('Empresa.dadosEmpresa')->with('empresa', $empresa)->with('action', URL::route('empresa_update', ['id', $empresa->id]))->with('method', 'PATCH');
}
这是我使用错误处理程序的“尝试”:
public function render($request, Exception $exception)
{
if ($e instanceof ModelNotFoundException)
{
//this is just giving me a completely blank response page
return 'Empresa não encontrada';
}
return parent::render($request, $exception);
}
实际如何完成?
首先,Laravel要做的是,如果DB中没有给定id的Model Row,它将自动发送404响应。
因此,如果要显示自定义视图,则需要自定义错误处理。 因此,在RouteServiceProvider
文件中,确保使用第3个参数(如RouteServiceProvider
引发自定义异常:
public function boot()
{
parent::boot();
Route::model('empresa', App\Empresa::class, function () {
throw new NotFoundEmpresaModelException;
});
}
然后在渲染函数中执行与之前尝试相同的操作。
我建议您不要使用模型注入功能,而应自己处理请求。 因此,请按原样使用empresa id值,然后尝试查找正确的数据,如果找不到,则进行自定义逻辑。 那应该很容易进行。
public function edit(Request $request, $empresa)
{
$empresaObj = Empresa::find($empresa);
if (!$empresa) {
return 'Empresa não encontrada';
}
return view('Empresa.dadosEmpresa')->with('empresa', $empresa)->with('action', URL::route('empresa_update', ['id', $empresa->id]))->with('method', 'PATCH');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.