Laravel View Components Package

Packages

June 1st, 2018

view-components-package.png

We featured View Components in Laravel, written by Jeff Ochoa, as an alternative approach to View Composers.

Inspired by Jeff’s article, Sebastian De Deyne of Spatie created a Laravel package that brings the concept of a View Component to Laravel applications. The package headline is: “A better way to connect data with view rendering in Laravel.”

One of the nice things about this approach over using view composers, is that view components help organize logic and data tied to a view in one place:

The benefit over view composers is that data and rendering logic are explicitly tied together in components instead of being connected afterwards. They also allow you to seamlessly combine properties and dependency injection.

Overview

The overall concept of a view component, is using the @render directive in a template. For example:

1@render(App\Http\ViewComponents\NavigationComponent::class, ['backgroundColor' => 'black'])

The first argument in the @render directive ties back to a class that implements the HtmlAble contract. For example, the following component is from the package’s readme:

1namespace App\Http\ViewComponents;
2
3use Illuminate\Http\Request;
4use Illuminate\Contracts\Support\Htmlable;
5
6class NavigationComponent implements Htmlable
7{
8 /** \Illuminate\Http\Request */
9 private $request;
10
11 /** @var string */
12 private $backgroundColor;
13
14 public function __construct(Request $request, string $backgroundColor)
15 {
16 $this->request = $request;
17 $this->backgroundColor = $backgroundColor;
18 }
19
20 public function toHtml(): string
21 {
22 return view('components.navigation', [
23 'activeUrl' => $this->request->url(),
24 'backgroundColor' => $this->backgroundColor,
25 ]);
26 }
27}

Rendering

You can render view components by referencing the component’s fully qualified name (as seen above), or a string class name:

1@render('navigationComponent', ['backgroundColor' => 'black'])

Since the component can be anything that implements the HtmlAble contract, you are not required to only using blade views to render components. Check the package’s readme for an example of wrapping an HTML package in a component.

Learn More

Check out the GitHub project to learn more about using this package. I’d also encourage you to read the original post on view components in Laravel that inspired this package.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners