Only until March 18th: coupon LARAVEL12 for 40% off Yearly/Lifetime membership!

Read more here
Courses

How to Structure Laravel 11 Projects

Repeating Responses: BaseController or Traits?

Summary of this lesson:
- Creating Base Controller for common responses
- Implementing API response Traits
- Reusing response patterns
- Managing consistent API responses

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 11 lessons of this course? (56 min read)

You also get:

  • 71 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord