A while ago, I published an article Introducing View Components in Laravel as an alternative to Laravel's View Composers, in this article I'll give you another option to create simple standalone components to use in your Blade views.
Creating a simple menu component class
Take a look at the following class:
As you can see, the only thing you need here is to use the __toString()
method that will return an HTML string.
The __toString() method allows a class to decide how it will react when it is treated as a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted. Learn more
Then on any blade-view, you’ll be able to “render” this component as follows:
{!! new MenuComponent() !!}
Adding a static method to improve readability
In your component class, you can add the following make()
method:
Then your view can be updated as follows:
{!! MenuComponent::make() !!}
Wrapping up
This approach will allow you to create a standalone class to keep your code SOLID; also, it will help you to keep your controllers clean and simple.
If you liked this approach, I'd suggest you take a look at the laravel-view-components developed by the Spatie team.
https://github.com/spatie/laravel-view-components#card