【问题标题】:Laravel firstOrFail functions redirects to wrong routeLaravel firstOrFail 函数重定向到错误的路由
【发布时间】:2019-08-06 15:58:23
【问题描述】:

信息:我所有的路线都像这样/locale/something 例如/en/home 工作正常。

在我的控制器中,我正在使用firstOrFail() 函数。

当触发失败部分时,该函数会尝试将我发送到/home。 这不起作用,因为它必须是/en/home

那么如何调整firstOrFail() 功能以将我发送到/locale/home ? 需要改变什么?

【问题讨论】:

  • Fail 会引发异常,然后在 Exceptions\Handler 类中进行处理,并显示错误页面。因此,您可能正在自己处理此问题并重定向到 home
  • 通常它会返回 404 而不会重定向到另一个 url。检查您的异常处理程序。

标签: php laravel laravel-5 exception request


【解决方案1】:

您可以通过多种方式处理它。

具体做法

您可以在每次找不到记录时重定向到特定视图的任何地方用 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()方法的地方处理这个问题。

全球方式

如 cmets 建议的那样,您可以在 Global Exception Handler 中定义它:

app/Exceptions/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);
}

【讨论】:

  • @q55awr 很高兴为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 2021-12-23
  • 2020-05-26
  • 2017-05-12
  • 2021-12-17
  • 2017-06-19
  • 2021-04-26
相关资源
最近更新 更多