Skip to main content

Repeating Responses: Base Controller or Trait?

Premium
3:41

The Full Lesson is Only for Premium Members

Want to access all of our courses? (36 h 00 min)

You also get:

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

Already a member? Login here

Taboritis avatar

You forgot return statement in your store method.

ex3m avatar

What about returning a Resource - JsonResource : php UserResource::make($data)

Adriano Y. avatar

When would you use a base controller and when would you use a trait?

Povilas Korop avatar

As everything in this course, it's a totally personal preference, you can use whichever you want.

👍 2
Sergio Sánchez avatar

In the case of API Responses, I use a Macro function using the Response class (based on one of your videos). It's another solution to not repeating the responses. Is it a good option? Or is just another option to solve the same "problem"?

Povilas Korop avatar

Yes, that's just one of the ways, as good as any other way.

👍 1
Pēteris avatar

Found very useful. Thank you.

Bevatel avatar

What about using trait but only on the desired class such as (UsersController.php) not on the general parent Controller.php because it will be generally extended on all controllers which might not need or use these API methods.

Povilas Korop avatar

Yes, that's also possible if that's what you want to do.

Nolan avatar

does Laravel's [https://laravel.com/docs/10.x/eloquent-resources#resource-responses] response now resolve that trait / controller question ? i.e.** php artisan make:resource UserResource** then use that as static in route, jobs, etc.

Route::get('/user/{id}', function (string $id) { return new UserResource(User::findOrFail($id)); });

Povilas Korop avatar

Your code is valid, your case is only one case of many others, not everyone uses APIs. Or maybe I missed your point on how exactly Laravel solves this.

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.