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:
- Use "General" Controller
- Use Traits
Option 1. General Controller.
If you generate a Controller with php artisan make:controller
, you should see it extends a...