Follow on twitter
Jun 2nd, 2019

Simple view components for your Laravel applications

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:

<?php
class MenuComponent
{
public function __toString()
{
// build your $menu data
return view('partials.menu', ['menu' => $menu])->render();
}
}
view raw 1.php hosted with ❤ by GitHub

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:

<?php
class MenuComponent
{
public static function make()
{
return new static();
}
public function __toString()
{
// build your $menu data
return view('partials.menu', ['menu' => $menu])->render();
}
}
view raw 2.php hosted with ❤ by GitHub

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.

spatie/laravel-view-components

A better way to connect data with view rendering in Laravel - spatie/laravel-view-components

Jeff
2 months ago
Share: