0

当我开始使用 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);
}

这真的是怎么做到的?

4

1 回答 1

2

1.正式的方式(但真的需要这样定制吗?)

首先,Laravel 所做的是,如果 DB 中没有具有给定 id 的 Model Row,它会自动发送 404 响应。

如果在数据库中没有找到匹配的模型实例,则会自动生成 404 HTTP 响应。

所以如果你想展示你的自定义视图,你需要自定义错误处理。所以在RouteServiceProvider文件中,确保它使用第三个参数抛出自定义异常,如下所示:

public function boot()
{
    parent::boot();

    Route::model('empresa', App\Empresa::class, function () {
        throw new NotFoundEmpresaModelException;
    });
}

然后在渲染函数中执行与您之前尝试过的相同的操作。

2. 休闲方式 - 很容易走

我宁愿建议你不要使用模型注入能力,而是自己处理请求。所以取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');
}
于 2017-01-29T23:30:24.203 回答