Reputation: 3205
Is there some way to return JSON from laravel by using something similar to abort()
function.
From controller returning JSON is easy we can just call
return response()->json(['message' => 'my mesage'], 200);
But from some other place (custom class for example) to return JSON I have to create a return chain to the contoller.
Is there a way to return json without resorting to a return chain.
Like using abort()
function.
I would like to use something similar to abort(400, 'my message')
but insted of returning html like abort does return JSON.
or is there a way to overwrite abort
to return JSON.
I would be thankfull solution that works for laravel 5.3 and up.
Upvotes: 1
Views: 2228
Reputation: 40653
First of all if you find yourself wondering such things you need to review your code.
The controller should get data which the controller is responsible for generating the appropriate response for. You shouldn't delegate response making to just about everywhere
You also should avoid abort
outside controllers, you should throw proper exceptions.
That being said here's a fat ugly hack for you:
Create an exception:
class JsonResponse extends Exception {
private $data;
public __construct($data, $message = null, $code = 0, $previous = null) {
$this->data = $data;
parent::__construct($message,$code,$previous);
}
}
In your Exception handler : usually App\Exceptions\Handler
protected $dontReport = [
// other lines
JsonResponse::class //
];
public function render($request, Exception $exception) {
if ($exception instanceof JsonResponse) {
return reponse()->json($e->getData());
}
//Other lines
}
Then whenever you need to immediately return a JSON response just do:
throw new JsonResponse($data);
However this obviously fails within try-catch blocks.
Upvotes: 4