DEV Community

Yossi Abramov
Yossi Abramov

Posted on • Originally published at

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:

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.


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.


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:


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.


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:

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

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:

    Lorem ipsum dolor sit amet consectetur, adipisicing elit. Corporis, fuga.


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 :-)

Top comments (0)