Laravel Target class [PagesController] does not exist error in Handler - php

My final goal is to use data from the database to display on the 404 page.
I have added the following code to my Handler.php in render method:
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('errors.' . '404', [], 404);
}
}
Content of errors.404.blade.php is only "test".
I have checked the name of the PagesController file, and it is capitalized as it should. I've also tried to empty the cache with Artisan::call('route:clear');, Artisan::call('cache:clear');, Artisan::call('cache:clear');, and Artisan::call('view:clear'); (I don't have access to the terminal directly).
Any help is appreciated.
Thanks.
Edit: This is the full handler file:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\App;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* #var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* #param \Exception $exception
* #return void
*
* #throws \Exception
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Symfony\Component\HttpFoundation\Response
*
* #throws \Exception
*/
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('errors.' . '404', [], 404);
}
}
return parent::render($request, $exception);
}
}

try this code
if ($exception instanceof UnauthorizedException) {
return response()->view('errors.403', [], 403);
}
return parent::render($request, $exception);

Related

How to redirect the wrong route method to error page in laravel, "The GET method is not supported for this route. Supported methods: POST"

I want to redirect my post route to error page if the request is not made with post but with get method. But i am getting the error "The GET method is not supported for this route. Supported methods: POST."
My route file
Route::get('/user/create',[UserController::class, 'create'])->name('user.create');
Route::post('/user',[UserController::class, 'store'])->name('user.store');
Into my controller i have used
public function store(Request $request){
if($request->isMethod('POST')){
dd($request->all());
}else{
return abort(404);
}
}
So when the route is Route::post('/user',[UserController::class, 'store'])->name('user.store'); for submitting the data by post method the url is http://127.0.0.1:8000/admin/user ok i dont have any problem with that, but when i do hit into my urlbar http://127.0.0.1:8000/admin/user with get method i get the above error but i dont want to show that rather it should get redirected to error page.
It's the logic to get a bad method error when someone is requesting a bad method but you can do something like this:
routes file:
Route::any('/user',[UserController::class, 'store'])->name('user.store');
and in controller:
public function store(Request $request){
if(! $request->isMethod('POST')){
return abort(404);
}
// and the rest of your code for the post request.
}
In case you don't want to edit the routes you can replace the exception.
in app/Exceptions/Handler.php add render method:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* #var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* #var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* #return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Throwable $e
* #return \Symfony\Component\HttpFoundation\Response
*
* #throws \Throwable
*/
public function render($request, Throwable $e)
{
if ($e instanceof MethodNotAllowedHttpException) {
return abort(404);
}
return parent::render($request, $e);
}
}

How to create a custom error page with variables in laravel 8

Good morning everyone, how to create a custom error page with variables in laravel 8 ? So, I want to display an error page with #extend('layouts.app') where in this layouts.app I give a variable such as $general to display the data in the generals table.
I've tried with the code below, but the result is still Undefined variable: general.
Exceptions\Handler.php
<?php
namespace App\Exceptions;
use App\Models\General;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Auth\AuthenticationException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* #var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* #return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = Arr::get($exception->guards(), 0);
$route = 'login';
if ($guard == 'admin') {
$route = 'admin.login';
}
return redirect()->route($route);
}
public function render($request, Throwable $exception)
{
if($this->isHttpException($exception)){
switch ($exception->getCode()) {
case 404:
//return redirect()->route('404');
$general = General::find(1);
return response()->view('errors.404', ['general' => $general], $exception->getCode());
break;
case 405:
return response()->view('errors.405', [], $exception->getCode());
break;
case 500:
return response()->view('errors.500', [], $exception->getCode());
break;
}
}
return parent::render($request, $exception);
}
}
errors\404.blade.php
#extends('layouts.front')
#section('title', __('Not Found'))
#section('code', '404')
#section('message', __('Not Found'))
what is the correct way to add variables in laravel 8 error page? thanks :)
You can create your own service provider (or just use App\Providers\AppServiceProvider)
In boot method register View::composer, which will listen on error-page views
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
// Using closure based composers...
View::composer('errors::404', function ($view) {
$general = General::find(1);
$view->with('general', $general);
});
}
you can also use wildcard 'errors::*'

php fatal error: cannot redeclare App\Exceptions\Handler::render() in G:\Xampp\htdocs\blog\app\Exceptions\Handler.php on line 55

I am creating a User Roles and Permissions using laravel 5.8, and in that when I want to run PermissionTableSeeder and i run in cmd like this:
php artisan db:seed --class=PermissionTableSeeder .
But it showing this error:
php fatal error: cannot redeclare App\Exceptions\Handler::render() in
G:\Xampp\htdocs\blog\app\Exceptions\Handler.php on line 55 and this is
my code:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that are not reported.
*
* #var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* #param \Throwable $exception
* #return void
*
* #throws \Exception
*/
public function report(Throwable $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Throwable $exception
* #return \Symfony\Component\HttpFoundation\Response
*
* #throws \Throwable
*/
public function render($request, Throwable $exception)
{
return parent::render($request, $exception);
}
public function render($request, Exception $exception) {
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->json(['User have not permission for this page access.']);
}
return parent::render($request, $exception);
}
}
You cannot declare/create two function with same name as below:
public function render($request, Throwable $exception) {
return parent::render($request, $exception);
}
public function render($request, Exception $exception) {
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->json(['User have not permission for this page access.']);
}
To solve this remove first function and add parent::render($request, $exception); in other as below
public function render($request, Exception $exception) {
return parent::render($request, $exception); // add here
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->json(['User have not permission for this page access.']);
}

Laravel localization in 404 page

Hello I have an issue with laravel localization
I've made language switcher and currently selected language doesn't work on 404 pages (it works if I return abort(404) in controller manualy), it always shows content on default locale defined in config/app.php
My middleware code
<?php
namespace App\Http\Middleware;
use Closure;
class SetLanguageCookie
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->hasCookie('language')) {
$cookie = $request->cookie('language');
app()->setLocale($cookie);
return $next($request);
} else {
$response = $next($request);
$response->withCookie(cookie()->forever('language', 'en'));
return $response;
}
}
}
Any ideas how can I make this working? So all automaticaly shown 404 pages show content in currently selected language?
If you have default error handling, look for this file:
app\Exceptions\Handler.php
Change the render method to something like this:
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if($e instanceof NotFoundHttpException)
{
if(\Request::hasCookie('language')) {
$cookie = \Request::cookie('language');
app()->setLocale($cookie);
//.... etc
}
}
return parent::render($request, $e);
}
Fixed it with help of #ArthurSamarcos
app/Exceptions/Handler.php
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
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);
}

Laravel request validation throwing HttpResponseException in version 5.2

I'm trying to update Laravel from version 5.1 to 5.2 in my project, I have followed this upgrade guide from the documentation, but now I'm getting this HttpResponseException when a validation fails
* Handle a failed validation attempt.
*
* #param \Illuminate\Contracts\Validation\Validator $validator
* #return mixed
*
* #throws \Illuminate\Http\Exception\HttpResponseException
*/
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException($this->response(
$this->formatErrors($validator)
));
}
In 5.1, the framework redirected to the previous url automatically with the validation errors.
This is my validation request
namespace domain\funcao\formRequest;
use autodoc\Http\Requests\Request;
class StoreFuncaoRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'codigo' => 'required|max:255|unique:funcao,codigo,'.$this->input('id').',id,deleted_at,NULL',
'nome' => 'required|max:255|unique:funcao,nome,'.$this->input('id').',id,deleted_at,NULL'
];
}
}
I have already updated my Exceptions Handler according to the guide
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
\Illuminate\Auth\Access\AuthorizationException\AuthorizationException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Foundation\ValidationException\ValidationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
];
...
}
Did someone had this problem??
I found the cause for this error, I was calling PrettyPageHandler from Whoops manually in my Exception Handler class.
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
\Illuminate\Auth\Access\AuthorizationException\AuthorizationException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Foundation\ValidationException\ValidationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
];
...
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// I just needed to remove this call to get rid of the problem
if (config('app.debug'))
{
return $this->renderExceptionWithWhoops($e);
}
return parent::render($request, $e);
}
/**
* Render an exception using Whoops.
*
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
protected function renderExceptionWithWhoops(Exception $e)
{
$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler());
return new \Illuminate\Http\Response(
$whoops->handleException($e),
$e->getStatusCode(),
$e->getHeaders()
);
}
}
I'm still using Whoops, but now automatically through Laravel Exceptions
This was the first question I came across when I had this problem although for me it was with Sentry not Whoops.
Here's a couple of exceptions and how I dealt with them:
public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException) {
return redirect()->back()->withInput()->with('error', 'Your Session has Expired');
}
if ($e instanceof HttpResponseException) {
return $e->getResponse();
}
return response()->view('errors.500', [
'sentryID' => $this->sentryID,
], 500);
}
I handle the HttpResponseException by simply returning the response the same way the ExceptionHandler class does.
All you have to do is, just write your business logics inside the protected failedValidation() inside your custom FormRequest class like follows
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
/**
* [failedValidation [Overriding the event validator for custom error response]]
* #param Validator $validator [description]
* #return [object][object of various validation errors]
*/
public function failedValidation(Validator $validator) {
// write your business logic here otherwise it will give same old JSON response
throw new HttpResponseException(response()->json($validator->errors(), 422));
}

Categories