Laravel Livewire: Components or Controllers?

Viewed 6643

I'm learning to use Livewire, and I see that I can use Components like Controllers, so far I have been able to manage views, data, and make some CRUD operations with Route Model Binding inside components.

Should I use components instead of controllers? Or should I keep using controllers and use the components just for frontend stuff?

Which is the best practice?

1 Answers

It totally depends on how you feel comfortable when structuring your application. Neither way is a best practice as such, but you may appreciate the consistency of using components everywhere.

I've seen some Livewire apps that take a minimal approach and just nest Livewire components within their standard controller-driven app. If you're easing an existing app into Livewire, this is perfect as it allows you to transition parts of it at a time. However, it's not the approach I would take if I were building an app from scratch.

I prefer to ditch controllers altogether. I enjoy having a complete Livewire component hierarchy that represents my app, with my page components at primary level, and then any nested components in a directory of the same name. Let's take this example -

app/Http/Livewire
- Account.php                   < Account page component
- Account                       < Account page nested components directory
  - UpdateNameForm.php          < Nested update name component
  - UpdatePasswordForm.php      < Nested update password component
  - DeleteForm.php              < Nested account deletion component
- Dashboard.php                 < Dashboard page component

To me, it really doesn't matter if some of my page components are static. There's not really any significant performance overhead of using Livewire to render a view as opposed to a controller. You know exactly where to look for lots of your application logic, without digging to see if a page is dynamic or not. You're also able to benefit from some sweet features that Livewire provides, such as route model binding using a typed component property. You can even remove your component's render() method if you are following the default file naming conventions.

Related