Courses

PHP for Laravel Developers

Controller Response Methods: "General" Controller or Traits

Summary of this lesson:
- Learn strategies for standardizing API responses
- Understand inheritance and traits in controller design
- Explore methods to create reusable response handling
- Examine approaches to implementing consistent API responses

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

You also get:

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