Jens Segers on Feb 07 2015

Adding Whoops back to Laravel 5

If you have ever used Laravel 4, you have probably seen the following Whoops error screen÷

whoops

In Laravel 5, Taylor Otwell decided not to include the package by default anymore. Whether this was a good decision or not is up for discussion. But luckily for us, Laravel 5 has made it super easy for us to add it back again.

First, grab the whoops package:

composer require filp/whoops --dev

Then, in your error handler, located in app/Exceptions/Handler.php, simply add the following lines to the render method:

/**
 * 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 (config('app.debug'))
    {
        $whoops = new \Whoops\Run;
        $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);

        return response($whoops->handleException($e),
            $e->getStatusCode(),
            $e->getHeaders()
        );
    }

    return parent::render($request, $e);
}

If you want Whoops to return a JSON response for AJAX requests, you can add a different handler 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 (config('app.debug'))
    {
        $whoops = new \Whoops\Run;

        if ($request->ajax())
        {
            $whoops->pushHandler(new \Whoops\Handler\JsonResponseHandler);
        }
        else
        {
            $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
        }

        return response($whoops->handleException($e),
            $e->getStatusCode(),
            $e->getHeaders()
        );
    }

    return parent::render($request, $e);
}

This should enable the Whoops error handler when your application is in debug mode. If you prefer to use a package, be sure to check out Graham Campbell's package.


Comments

farid 2 months ago

2 years later still being nice and usefull. Cheers.


Vadims 2 years ago

+1! Nice


Jason 2 years ago

Thank you for this. I really missed the fuller output of the Whoops package, not to mention the the prettier debug pages.


jenssegers 2 years ago

Thanks @rimipelhate, fixed it :)


remipelhate 2 years ago

Very useful, indeed! Thanks! Just noticed a small typo in the Json response: you're missing the closing bracket after JsonResponseHandler ;)


wouterds 2 years ago

Very useful, thanks!