1

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.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is exactly what i was looking for. I do understand that this method is a hack if used to return data. I was looking for a way to return JSON error messages when Accept: application/json is not in request header

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.