Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Controller Response Methods: "General" Controller or Traits

Premium
4 min read

Now, I want to show you another practical example of Inheritance and Traits. What if you want to have strict rules for API responses instead of calling return response()->json() in every Controller method?

For example, see this code:

TaskController:

public function index()
{
return response()->json([
'success' => true,
'data' => Task::paginate()
]);
}

As you can see, the API client expects success => true to be returned and the actual data in a data key.

But you don't have any guarantees that other developers on your team (including your future self) will remember to use this structure in other Controllers/methods. How do we "enforce" it?

The answer is to create specific methods to be used, like $this->respondSuccess(), $this->respondError(), and others. The question is WHERE to create them to be used in all Controllers?

I will show you two ways:

  1. Use "General" Controller
  2. Use Traits

Option 1. General Controller.

If you generate a Controller with php artisan make:controller, you should see it extends a...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

AS
Abdulbasit Salah ✓ Link copied!

this my response method that use in BaseController

protected function jsonResponse($result = true, $message = "", $code = 200, $data = null, $error = null) { $response = [ 'result' => $result, 'status' => $code, 'message' => $message, ];

    if ($data !== null || is_array($data)) {
        $response['data'] = $data;
    }

    if ($error) {
        $response['errors'] = $error;
    }

    return response()->json($response, 200);

}