Courses

How to Structure Laravel 9 Projects

Repeating Responses: Base Controller or Trait?

Previous: Dispatch an Event and Let Others Listen to it
avatar

You forgot return statement in your store method.

avatar

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

avatar
You can use Markdown
avatar

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

avatar

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

avatar
You can use Markdown
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"?

avatar

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

avatar
You can use Markdown
avatar

Found very useful. Thank you.

avatar
You can use Markdown
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.

avatar

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

avatar
You can use Markdown
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)); });

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.

avatar
You can use Markdown
avatar
You can use Markdown