What version of Laravel are you using? If it's 5.5, you can create custom Exception classes and return a certain type of response only with that exception. If you're using anything above 5.0 but less than 5.5, you can check for the instance in the Handler class inside of the render() function. I like to make an exception that I call GeneralException that I can throw during any Ajax requests that I make.
Before 5.5:
// This is coming from the Handler.php class
public function render($request, Exception $exception)
{
if ($exception instanceof GeneralException) {
return response()->json(['error' => true, 'message' => $exception->getMessage()]);
}
return parent::render($request, $exception);
}
Using 5.5:
<?php
namespace App\Exceptions;
use Exception;
/**
* Class GeneralException
*/
class GeneralException extends Exception
{
/**
* Any extra data to send with the response.
*
* @var array
*/
public $data = [];
/**
* The status code to use for the response.
*
* @var integer
*/
public $status = 422;
/**
* Create a new exception instance.
*
* @param string $message
*/
public function __construct($message)
{
parent::__construct($message);
}
/**
* In Laravel 5.5, you can render your exceptions directly from the exception class
* itself, allowing you to handle them they way you want to.
*/
public function render($request)
{
if ($request->expectsJson()) {
return $this->handleAjax();
}
return redirect()->back()
->withInput()
->withErrors($this->getMessage());
}
/**
* Handle an ajax response.
*/
private function handleAjax()
{
return response()->json([
'error' => true,
'message' => $this->getMessage(),
'data' => $this->data
], $this->status);
}
/**
* Set the extra data to send with the response.
*
* @param array $data
*
* @return $this
*/
public function withData(array $data)
{
$this->data = $data;
return $this;
}
/**
* Set the HTTP status code to be used for the response.
*
* @param integer $status
*
* @return $this
*/
public function withStatus($status)
{
$this->status = $status;
return $this;
}
}
If you really want exceptions specific for every error, by all means make them, but I feel using this approach works for most cases in the application.