DEV Community

Yossi Abramov
Yossi Abramov

Posted on • Originally published at yossiabramov.com

Laravel 7 Class Based Components – Part I

The following is an excerpt from a post I published on my blog. The full post is available here: https://yossiabramov.com/blog/laravel-7-class-based-components-part-i

With Laravel 7.x we now have two new approaches or ways of writing our blade components: class based components and anonymous components. In this post I will focus on creating and including class based components as well as passing data to them.

Create

We can create components with an artisan command:

php artisan make:component Header

This will create two files: app/View/Components/Header.php and resources/views/components/header.blade.php.

Class

In the folder app/View/Components/ will now have a Header class that will help us in handling our component’s logic. The Header class will look like this:

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Header extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.header');
    }
}

As you can see, our Header class has a render() function that renders our view. We will return to this class again after having a quick look at our view.

View

In the folder resources/views/components/ we will now have a header.blade.php blade file that will contain our blade view. header.blade.php will look like this:

<div>
    <!-- Well begun is half done. - Aristotle -->
</div>

Nothing but a div and an inspirational quote! 💪 . BTW, you can generate more of these amazing quotes by running:

php artisan inspire

Let’s add some hardcoded content to our header.blade.php so we can see it in action:

<div>
    Lorem ipsum dolor sit amet consectetur, adipisicing elit. Corporis, fuga.
</div>

Include

Including our component is a bit different from previous Laravel versions:

<x-header />

Quick Example

Here is a quick example for creating and including a component with more than one word in its name.

Let’s create the component SpecialHeading:

php artisan make:component SpecialHeading

This will create two files: app/View/Components/SpecialHeading.php and resources/views/components/special-heading.blade.php.

And this is how you would include it:

<x-special-heading /> 

Read the full post on my website :-)
https://yossiabramov.com/blog/laravel-7-class-based-components-part-i

Top comments (0)