Bird
0
0

You want to create a single action controller that returns a JSON response with a message 'Success'. Which code snippet correctly implements this?

hard📝 Application Q15 of 15
Laravel - Controllers
You want to create a single action controller that returns a JSON response with a message 'Success'. Which code snippet correctly implements this?
Aclass JsonResponseController { public function __invoke() { return json_encode(['message' => 'Success']); } }
Bclass JsonResponseController { public function __invoke() { return response()->json(['message' => 'Success']); } }
Cclass JsonResponseController { private function __invoke() { return ['message' => 'Success']; } }
Dclass JsonResponseController { public function handle() { return json(['message' => 'Success']); } }
Step-by-Step Solution
Solution:
  1. Step 1: Use __invoke method for single action controller

    The controller must have a public __invoke() method to be a single action controller.
  2. Step 2: Return a proper JSON response in Laravel

    Use Laravel's response()->json() helper to return a JSON response correctly.
  3. Final Answer:

    class JsonResponseController { public function __invoke() { return response()->json(['message' => 'Success']); } } -> Option B
  4. Quick Check:

    __invoke + response()->json() = class JsonResponseController { public function __invoke() { return response()->json(['message' => 'Success']); } } [OK]
Quick Trick: Use response()->json() inside __invoke method [OK]
Common Mistakes:
  • Using handle() instead of __invoke()
  • Returning raw arrays without response helper
  • Using json() function which doesn't exist in Laravel

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes