简体   繁体   English

Laravel firstOrFail函数重定向到错误的路由

[英]Laravel firstOrFail functions redirects to wrong route

Info: All my routes look like this /locale/something for example /en/home works fine. 信息:我所有的路线都像/locale/something ,例如/en/home可以正常工作。

In my controller I'm using the firstOrFail() function. 在我的控制器中,我正在使用firstOrFail()函数。

When the fail part is triggered the function tries to send me to /home . 当失败部分被触发时,该函数尝试将我发送到/home Which doesn't work because it needs to be /en/home . 这不起作用,因为它必须是/en/home

So how can I adjust the firstOrFail() function to send me to /locale/home ? 那么,如何调整firstOrFail()函数将我发送到/locale/home What needs to changed ? 需要改变什么?

You can treat it in several ways. 您可以通过几种方式对其进行处理。

Specific approach 具体做法

You could surround your query with a try-catch wherever you want to redirect to a specific view every time a record isn't found: 每次找不到记录时,只要要将查询重定向到特定视图,都可以在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..
    }

  }

The only downside of this is that you need to handle this everywhere you want to use the firstOrFail() method. 唯一的缺点是,您需要在要使用firstOrFail()方法的任何地方进行处理。

The global way 全球方式

As in the comments suggested, you could define it in the Global Exception Handler : 如建议的注释所示,您可以在Global Exception Handler中定义它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM