Reputation: 1
I am working on a php project with laravel where i used errors->any()
to capture all errors and display them with toastr lib within my script.
The issue now is that when I implemented a 404 error page, the toastr is not able to catch the error and hence the website breaks.
Please what could i do so that the toastr lib displays errors only when the error is coming from validations and notifications and not when the error is due to 404 page not found?
See below the the codes in the exceptions -> handler.php , that displays the 404 pages. ( I actually have two 404 pages, one for admin and the other for the website).
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
public function render($request, Throwable $exception)
{
if ($exception instanceof NotFoundHttpException) {
// Check if the URL starts with '/admin' to differentiate between the areas
if ($request->is('admin/*')) {
// Return the custom admin 404 view
return response()->view('errors.404-admin', [], 404);
}
// Return the custom website 404 view for all other pages
return response()->view('errors.404-website', [], 404);
}
return parent::render($request, $exception);
}
This is the code in my script
<script>
@if($errors->any())
@foreach ($errors->all() as $error )
toastr.error('{{$error}}');
@endforeach
@endif
</script>
<script>
When I comment out the error/toastr code in the script, the 404 error pages were able to display very well. But I was not able to get validation errors displayed from my pages.
Error i get when I try to display the 404 page with the toastr code in the script
Upvotes: 0
Views: 28
Reputation: 72
You can pass the
$is404 = true;
like
return response()->view('errors.404-admin', ['is404' => $is404], 404);
on return response to the blade view
and check it in the script
<script>
@if(isset($is404) && $is404)
// do nothing
@else
@if($errors->any())
@foreach ($errors->all() as $error )
toastr.error('{{$error}}');
@endforeach
@endif
@endif
</script>
other than you can try this also
<script>
@if(!empty($errors) && $errors->any())
@foreach ($errors->all() as $error)
toastr.error('{{ $error }}');
@endforeach
@endif
</script>
Upvotes: 0