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? (30 h 09 min)

You also get:

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

Already a member? Login here

Comments & Discussion

T
Taboritis ✓ Link copied!

You forgot return statement in your store method.

E
ex3m ✓ Link copied!

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

AY
Adriano Y. ✓ Link copied!

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

PK
Povilas Korop ✓ Link copied!

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

SS
Sergio Sánchez ✓ Link copied!

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"?

PK
Povilas Korop ✓ Link copied!

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

P
Pēteris ✓ Link copied!

Found very useful. Thank you.

B
Bevatel ✓ Link copied!

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.

PK
Povilas Korop ✓ Link copied!

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

N
Nolan ✓ Link copied!

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)); });

PK
Povilas Korop ✓ Link copied!

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.