How can I get the laravel 4 debugger page in laravel 5 debugger
page
here
to
Install the whoops package:
composer require filp/whoops
Then use it to render your exceptions by editing your app/Exceptions/Handler.php:
<?php namespace App\Exceptions;
use Exception;
use Whoops\Run as Whoops;
use Illuminate\Http\Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use PragmaRX\Sdk\Services\ExceptionHandler\Service\Facade as SdkExceptionHandler;
class Handler extends ExceptionHandler {
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
public function report(Exception $e)
{
return parent::report($e);
}
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
if (env('APP_DEBUG'))
{
return $this->whoops($e);
}
return parent::render($request, $e);
}
protected function whoops(Exception $e)
{
$handled = with(new Whoops)
->pushHandler(new \Whoops\Handler\PrettyPageHandler())
->handleException($e);
return new Response(
$handled,
$e->getStatusCode(),
$e->getHeaders()
);
}
}
Related
Working with laravel 8 app started by other developer, I can not show
file /resources/views/errors/404.blade.php(I have this file) when invalid url like
http://127.0.0.1:8000/app_admin/platforms/2/editINVALID URL
I got empty page with 200 Status Code returned
in routes/web.php I see :
<?php
use Illuminate\Support\Facades\Route;
...
/* ========= For Adminside ========= */
Route::group(array('middleware' => 'auth_admin', 'prefix' => 'app_admin'), function() {
...
In file app/Http/Middleware/AuthenticatedAdmin.php I have :
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AuthenticatedAdmin
{
public function handle($request, Closure $next, $guard = null)
{
$uri = $request->path();
$bypass_uri = array('/app_admin', 'app_admin/login',
'app_admin/logout', 'app_admin/forgot_password');
if (!in_array($uri, $bypass_uri)) {
if (Auth::guard($guard)->check()) {
if (Auth::user()->urole == 1) {
// return redirect()->route('dashboard');
}
if (Auth::user()->urole == 0) {
return redirect()->url('/');
}
} else {
return redirect()->route('login');
}
}
return $next($request);
}
}
Also I try add logs into :
app/Exceptions/Handler.php :
<?php
namespace App\Exceptions;
//use Laravel\Fortify\Contracts\LogoutResponse;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
protected $dontReport = [
//
];
protected $dontFlash = [
'password',
'password_confirmation',
];
public function register()
{
$this->reportable(function (Throwable $e) {
\Log::info( varDump($e, ' -1 app/Exceptions/Handler.php register $e::') );
});
}
public function render($request, Throwable $e)
{
$response = parent::render($request, $e);
\Log::info( varDump($response->status(), ' -1 app/Exceptions/Handler.php render $response->status()::') );
if ($response->status() === 419) {
\Log::info( ' Expired' );
auth()->logout();
// return app(LogoutResponse::class);
}
if ($this->isHttpException($e)) {
if ($e->getStatusCode() == 404) {
return response()->view('errors' . '404', [], 404);
}
}
return $response;
}
}
I do not see any logs when I enter invalid url like :
http://127.0.0.1:8000/app_admin/platforms/2/editINVALID URL
How can it be fixed?
Thanks!
I added this code in handler.php
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login_page');
}
but when session destroyed, it does not redirect to login page.
I think you are doing it in a wrong section so in your Handler.php class create a report method
Laravel 7 and higher
public function report(Throwable $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login_page');
}
}
Laravel 6 and below
public function report(Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login_page');
}
}
In Laravel 8 or higher, go to app/Exceptions edit Handler.php and update the register method as follows-
public function register()
{
$this->renderable(function (\Exception $e) {
if ($e->getPrevious() instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login');
};
});
}
in return redirect()->route('login'); change you login to your login route.
Im doing a crud, i want to show item data using id, i have this in web.php:
Route::get('update/{id}', 'CrudController#update');
How can I deny that the user changes the id in the path to one that does not exist? That shows only those that exist and those that do not, that do not load?
In your update method, you can do the following:
public function update($id)
{
MyModel::findOrFail($id);
//...perform other actions
}
It will throw a 404 response if the requested $id is a non-existent one.
Then you can catch it if you want in the render() method of app\Exceptions\Handler.php:
use Illuminate\Database\Eloquent\ModelNotFoundException;
.
.
.
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
if ($request->wantsJson()) {
return response()->json([
'data' => 'Resource not found'
], 404);
} else {
abort(404);
}
}
return parent::render($request, $exception);
}
Or, If you do not want to go through all the trouble of configuring it in the handler, you could also do:
public function update($id)
{
if (! $model = MyModel::find($id)) {
abort(404);
}
//...perform other actions with $model
}
The abort(404) method takes the user to the default Page not found page of laravel, which is an appropriate thing to do.
In my my laravel 5.7.3 application I use https://github.com/jrean/laravel-user-verification extention and with use of
middleware I generate UserNotVerifiedException error when logged is not verified
But with excception I want to make logout and redirect to /login page and reading https://laravel.com/docs/master/errors#the-exception-handler doc in
file app/Exceptions/Handler.php I do :
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Auth;
use App\Exceptions\UserNotVerifiedException;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Foundation\Auth\RegistersUsers;
use Jrean\UserVerification\Traits\VerifiesUsers; // Do I need to add these declarations here ?
use Jrean\UserVerification\Facades\UserVerification;
class Handler extends ExceptionHandler
{
use RegistersUsers;
use VerifiesUsers;
protected $dontReport = [
//
];
protected $dontFlash = [
'password',
'password_confirmation',
];
public function report(Exception $exception)
{
parent::report($exception);
}
public function render($request, Exception $exception)
{
dump($exception);
if ($exception instanceof UserNotVerifiedException) {
dump("Make Logout");
Auth::logout();
return redirect('/admin/dashboard/index');
}
return parent::render($request, $exception);
}
}
In dump file I see first message, but not second(and why there is no redirection):
UserNotVerifiedException {#509 ▼
#message: "This user is not verified."
#code: 0
#file: "/mnt/_work_sdb8/wwwroot/lar/Votes/vendor/jrean/laravel-user-verification/src/Middleware/IsVerified.php"
#line: 26
trace: {▶}
}
Which is valid way ?
Thanks!
You can try to put the original namespace like:
if ($exception instanceof \Jrean\UserVerification\Exceptions\UserNotVerifiedException) {
dump("Make Logout");
Auth::logout();
return redirect('/admin/dashboard/index');
}
I'm starting out in Laravel and want to discover more about using error handling especially the ModelNotFoundException object.
<?php
class MenuController extends BaseController {
function f() {
try {
$menus = Menu::where('parent_id', '>', 100)->firstOrFail();
} catch (ModelNotFoundException $e) {
$message = 'Invalid parent_id.';
return Redirect::to('error')->with('message', $message);
}
return $menus;
}
}
?>
In my model:
<?php
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Menu extends Eloquent {
protected $table = 'categories';
}
?>
Of course for my example there are no records in 'categories' that have a parent_id > 100 this is my unit test. So I'm expecting to do something with ModelNotFoundException.
If I run http://example.co.uk/f in my browser I receive:
Illuminate \ Database \ Eloquent \ ModelNotFoundException
No query results for model [Menu].
the laravel error page - which is expected, but how do I redirect to my route 'error' with the pre-defined message? i.e.
<?php
// error.blade.php
{{ $message }}
?>
If you could give me an example.
In Laravel by default there is an error handler declared in app/start/global.php which looks something like this:
App::error(function(Exception $exception, $code) {
Log::error($exception);
});
This handler basically catches every error if there are no other specific handler were declared. To declare a specific (only for one type of error) you may use something like following in your global.php file:
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
// Log the error
Log::error($exception);
// Redirect to error route with any message
return Redirect::to('error')->with('message', $exception->getMessage());
});
it's better to declare an error handler globally so you don't have to deal with it in every model/controller. To declare any specific error handler, remember to declare it after (bottom of it) the default error handler because error handlers propagates from most to specific to generic.
Read more about Errors & Logging.
Just use namespace
try {
$menus = Menu::where('parent_id', '>', 100)->firstOrFail();
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
$message = 'Invalid parent_id.';
return Redirect::to('error')->with('message', $message);
}
Or refer it to an external name with an alias
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
When you use the render() function in Laravel 8.x and higher versions, you will encounter 500 Internal Server Error. This is because with Laravel 8.x errors are checked within the register() function (Please check this link)
I'm leaving a working example here:
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
class Handler extends ExceptionHandler
{
public function register()
{
$this->renderable(function (ModelNotFoundException $e, $request) {
return response()->json(['status' => 'failed', 'message' => 'Model not found'], 404);
});
$this->renderable(function (NotFoundHttpException $e, $request) {
return response()->json(['status' => 'failed', 'message' => 'Data not found'], 404);
});
}
}
Try this
try {
$user = User::findOrFail($request->input('user_id'));
} catch (ModelNotFoundException $exception) {
return back()->withError($exception->getMessage())->withInput();
}
And to show error, use this code in your blade file.
#if (session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
#endif
And of course use this top of your controller
use Illuminate\Database\Eloquent\ModelNotFoundException;