How to produce API error responses in Laravel 5.4? -


whenever make call /api/v1/posts/1, call forwarded show method

public function show(post $post) {     return $post; } 

in postcontroller.php resourceful controller. if post exist, server returns json response. however, if post not exist, server returns plain html, despite request expecting json in return. here's demonstration postman.

enter image description here

the problem api supposed return application/json, not text/html. so, here questions:

1. laravel have built-in support automatically returning json if exceptions occur when use implicit route model binding (like in show method above, when have 404)?

2. if does, how enable it? (by default, plain html, not json)

if doesn't what's alternative replicating following across every single api controller

public function show($id) {     $post = post::find($id); // findorfail() won't return json, plain html     if (!$post)         return response()->json([ ... ], 404);     return $post; } 

3. there generic approach use in app\exceptions\handler?

4. standard error/exception response contain? googled found many custom variations.

5. , why isn't json response still built implicit route model binding? why not simplify devs life , handle lower-level fuss automatically?

edit

i left conundrum after folks @ laravel irc advised me leave error responses alone, arguing standard http exceptions rendered html default, , system consumes api should handle 404s without looking @ body. hope more people join discussion, , wonder how guys respond.

  1. is there generic approach use in app\exceptions\handler?

you can check if json expected in generic exception handler.

// app/exceptions/handler.php public function render($request, exception $exception) {     if ($request->expectsjson()) {         return response()->json(["message" => $exception->getmessage()]);     }     return parent::render($request, $exception); } 

Comments