Skip to main content

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

Read more here

Repeating Responses: BaseController or Traits?

Premium
5 min read

Returning the result may be a repeating part of various Controllers, especially in API controllers. Why don't we refactor it to have less repeatable code?

For example, if you want to return a specific format in your API responses:

Any API Controller:

public function store(StoreUserRequest $request)
{
// ... Store operation
 
return response()->json([
'result' => 'success',
], 200);
}
 
public function update(StoreUserRequest $request, User $user)
{
// ... Update operation
 
return response()->json([
'result' => 'success',
], 200);
}

See the repeating part? Of course, they don't necessarily have to be identical, but some responses may be the same. So, what are our options? There are at least two ways how you can do that.


Option 1. Base Controller.

First, you can create the logic in the Base Controller, which is app/Http/Controllers/Controller.php:

abstract class Controller
{
public function respondOk($data)
{
return response()->json([
'result' => 'success',
'data' => $data,
], 200);
}
}

And then, in your "regular" Controller, which extends that Base Controller, the return would be changed to $this->respondOk().

public function store(StoreUserRequest $request)
{
$user = (new CreateUserAction())->execute($request->validated());
 
NewUserDataJob::dispatch($user);
NewUserRegistered::dispatch($user);
 
return response()->json([
'result' => 'success',
'data' => $user,
], 200);
return $this->respondOk($user);
}

This means that all Controllers will have access to that respondOk() method. But what if you want to pick and choose which Controllers would have this behavior?


Option 2. Traits.

Another option is to use Traits. This is useful when...

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

S
SopharmaGroup ✓ Link copied!

For Option 1. Base Controller.

I might be wrong, but should there be a "return" before $this->respondOk($user);?

return $this->respondOk($user);

M
Modestas ✓ Link copied!

Thank you, updated the lesson

CJ
Caleb Johnson ✓ Link copied!

I am not sure if I am missing something, but I don't see the updated reflected in the lesson.

C
ccarlosm ✓ Link copied!

Another option to this might be to create a Response macro: https://laravel.com/docs/11.x/responses#response-macros