信息:我所有的路线看起来像这样/locale/something
,例如/en/home
工作正常。
在我的控制器中,我正在使用该firstOrFail()
功能。
当触发失败部分时,该函数会尝试将我发送到/home
. 这不起作用,因为它需要是/en/home
.
那么我该如何调整firstOrFail()
发送给我的功能/locale/home
呢?需要改变什么?
您可以通过多种方式处理它。
您可以在每次未找到记录时重定向到特定视图的任何位置使用 try-catch 包围您的查询:
class MyCoolController extends Controller {
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Redirect;
//
function myCoolFunction() {
try
{
$object = MyModel::where('column', 'value')->firstOrFail();
}
catch (ModelNotFoundException $e)
{
return Redirect::to('my_view');
// you could also:
// return redirect()->route('home');
}
// the rest of your code..
}
}
唯一的缺点是您需要在要使用该firstOrFail()
方法的任何地方处理此问题。
正如建议的评论一样,您可以在Global Exception Handler 中定义它:
应用程序/异常/Handler.php
# app/Exceptions/Handler.php
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Redirect;
// some code..
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && ! $request->expectsJson())
{
return Redirect::to('my_view');
}
return parent::render($request, $exception);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句