简体   繁体   中英

Laravel firstOrFail functions redirects to wrong route

Info: All my routes look like this /locale/something for example /en/home works fine.

In my controller I'm using the firstOrFail() function.

When the fail part is triggered the function tries to send me to /home . Which doesn't work because it needs to be /en/home .

So how can I adjust the firstOrFail() function to send me to /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:

 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.

The global way

As in the comments suggested, you could define it in the 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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