Jens Segers on

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.

Webmentions

Tweet about this blog post and you will appear below!