Good morning all,
Laravel v7.+
I made a
$user = User::findOrFail($id);
on my controller, it works well but when I have no result it sends me to a 404 page.
I would like to be able to do a return back with error message.
Some are talking about try catch.
Do you have any other solution to optimize?
Thank you, good day, stay home!
If you are having this issue in a single Controller only, you can use try catch
If you need a more general solution, you can work with the exception render method (https://laravel.com/docs/master/errors#render-method) on the ModelNotFoundException
public function render($request, Throwable $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->view('errors.custom', [], 404);
}
return parent::render($request, $exception);
}
Alternative to try/catch
$user = User::find($id);
if(!$user){
return redirect()->back()->with(['error' => 'Error message']);
}
... your other logic here
Related
I have custom error pages e.g. resources/views/errors/404.blade.php everything is working just fine but the localization is not working for error pages. If I change website language the error pages still show in default language I tried in many way but its not working, Can anyone please help me make this work thanks in advance.
I try to make it work via exception handler but don't know how to do that. I can apply language middleware is someone can tell me where is default routes for error pages.
You can also redirect to other pages in App\Exceptions\Handler.php. You can also assign using App::setLocale(). Like this:
public function render($request, Throwable $exception)
{
App::setLocale('en_GB');
/** #var \Symfony\Component\HttpKernel\Throwable $e */
$e = $exception;
$statusCode = $e->getStatusCode();
return $this->isHttpException($exception) && $statusCode == 404 ?
response()->view('frontend.pages.404') :
parent::render($request, $exception);
}
Open app/exceptions/handler.php
find render function paste here
don't for get import this trait
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function render($request, Exception $e)
{
if($request->hasCookie('language')) {
// Get cookie
$cookie = $request->cookie('language');
// Check if cookie is already decrypted if not decrypt
$cookie = strlen($cookie) > 2 ? decrypt($cookie) : $cookie;
// Set locale
app()->setLocale($cookie);
}
if($e instanceof NotFoundHttpException) {
return response()->view('errors.404', [], 404);
}
return parent::render($request, $e);
}
thank you guys a little discussion with you guys fixed my problem I get the session's locale value in exception handler that worked for me I am answering it may be can help some one else. Below are the thing I did in App/Exception/Handler.php
use Session;
public function render($request, Throwable $exception)
{
app()->setLocale(Session::get('locale'));
return parent::render($request, $exception);
}
also i moved
\Illuminate\Session\Middleware\StartSession::class,
from web group to global group in kernal.php
public function render($request, Exception $exception)
{
if ( $request->route()->getPrefix() == 'api' ) {
some code......
return response()->json($response, $status);
}
return parent::render($request, $exception);
}
I have a website content site & api both.
I want my exception return json when user request api
If user request is not api, it will return the default page.
But when I put logic into function render, the default one got error.
Anyone know how to fix this?
I'm not quite sure what your question is. But you can detect if you should return a JSON response or not using the wantsJson() method. For example the code should instead read to say:
public function render($request, Exception $exception)
{
if ( $request->wantsJson()) {
some code......
return response()->json($response, $status);
}
return parent::render($request, $exception);
}
Laravel should automatically detect this and return a JSON response for exceptions if you are making a JSON request. The fact it isn't doing this, I would check to make sure you are making a JSON request and not a standard HTTP request.
Use $request->wantsJson() and check if the route is prefixed with api:
public function render($request, Exception $exception)
{
if ( $request->wantsJson() && $request->is('api/*')) {
some code......
return response()->json($response, $status);
}
return parent::render($request, $exception);
}
See here for wantsJson() method, and other useful Request methods: https://laravel.com/api/5.7/Illuminate/Http/Request.html#method_wantsJson
I was wondering if there is a way to catch all the exceptions that are thrown in a laravel app and store them in database ?
I have been looking at some packages but coudn't find anything that tells where and how to catch the exceptions.
for catch all errors and log them you need to edit App\Exceptions\Handler file like this
public function render($request, Exception $exception)
{
if ($exception){
// log the error
return response()->json([
'status' => $exception->getStatusCode(),
'error' => $exception->getMessage()
]);
}
return parent::render($request, $exception);
}
As stated in the Docs,
You need to have to customize the render() method of App\Exceptions\Handler.
Edit the app/Exceptions/Handler.php:
public function render($request, Exception $e)
{
$error =$e->getMessage();
//do your stuff with the error message
return parent::render($request, $exception);
}
I need to have a custom controller triggered when user hits a not-existing url or when I programmatically force an App::abort(404).
How can I do it?
My 404 views need some data, and a simple blade View (or a ViewComposer) is not enough.
Thanks
PS catch-all urls is not functional, because they don't catch programmatically launched 404.
Edit the render function of App\Exceptions\Handler class and add something about 404 here:
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
// Do what you want...
// You can even use the $request variable
}
Full example:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
echo 'hello from 404 renderer';
dd($request); // Or you can a view.
}
return parent::render($request, $exception);
}
Try to return a redirect() to your custom Controller instead of a response() from the Handler's render() method if the exception is 404. You can retrieve the the page requested from the $request then right ?
Here is the sample:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
return redirect(route('route.to.custom.controller'))->with('request', $request);
}
return parent::render($request, $exception);
}
Hope that will help, cheers !
I was trying to open Sandbox paypal page from my Laravel application and faced below issue
This issue came when internet connection was not available. Like we face 404 issue...for that we have 404 blade in View folder.
Is there any way to handle this exception so that we can show a user friendly page to user that Please check your internet connection
It doesn't not works when I write below code:
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
return response()->view('errors.InternetConnection');
}
but it works when I write
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
\App::abort(404);
}
I created a new blade called InternetConnection in error folder
You can listen for this exception in App\Exceptions\Handler#render. Just add this:
if ($e instanceof PayPalConnectionException) {
return response()->view('errors.404', [], 404);
}
Yes, you can! (https://laravel.com/docs/5.1/errors#the-exception-handler)
in your App\Exceptions\Handler:
...
public function render($request, Exception $e)
{
if ($e instanceof PayPalConnectionException) {
//my paypal exception
return response()->view('errors.payPalConnectionError', [], 404);
}
return parent::render($request, $e);
}
This will work:-
you need to create a folder named errors if not already exist in views and place blade file named 404.blade.php in it. and put your error template for 404 error in this blade. laravel will automatically use it when ever a 404 error will occur.
In your app/Exceptions/Handler.php edit render method as:
public function render($request, Exception $e)
{
if($e instanceof ValidationException) return response()->view('errors.abc');
return parent::render($request, $e);
}
Remember Don't forget to USE the Exception in your Handler.php
Like I am showing abc view for ValidationException So I am adding this line in my Handler.php class
use Illuminate\Validation\ValidationException;
Otherwise this won't work.