Reputation: 119
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 ?
Upvotes: 0
Views: 1210
Reputation: 14261
You can treat it in several ways.
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.
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);
}
Upvotes: 1