Create Custom View Components with Laravel Blade Templates

Learn how to implement your own view components in Laravel with this article. Implementing blade components can help reduce the redundancy of your code and keep it consistent across all the views that have the same style, layout, and element. Also, make it more maintainable by keeping the code in one place. Assuming, you have a website that lists jobs board that has the same style the only difference is the information (position, description, etc). By that can you create a job board component and reused it on the jobs board list and other pages that contain the job board.

To generate your component file Laravel provide the command below where CardComponent is the name of your component.

Now you will see 2 files CardComponent.php and card-component.blade.php

  • CardComponent.php where you construct data passed from the used component and assign/format to pass it to the custom component.
  • card-component.blade.php is where you write the style, and layout of your views and used the variable assigned in the CardComponent to show the necessary information.
php artisan make:component CardComponent

Now you will see 2 files CardComponent.php and card-component.blade.php

In CardComponent.php
<?php

namespace App\View\Components;

use Illuminate\View\Component;

class CardComponent extends Component
{
    public $image, $name, $position;

    /**
     * Create a new component instance.
     *
     * @return void
     */
    // construct data from x-card-component and assign to public variable to use in card-component.blade.php
    public function __construct($image = '', $name = '', $position = '')
    {
        $this->image = $image;
        $this->name = $name;
        $this->position = $position;
    }


    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.card-component');
    }
}
In card-component.blade.php
<div class="card">
    <img src="{{ $image }}" alt="photo" style="width:100%">
    <div class="container">
        <h4><b>{{ $name }}</b></h4>
        <p>{{ $position }}</p>
    </div>
</div>
<style>
    .card {
        box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
        transition: 0.3s;
    }
    .container {
        padding: 2px 16px;
    }
</style>

After that, you can call your component anywhere in the blade with this script and assign any data.

<x-card-component image="https://picsum.photos/300/300.jpg" name="Andy" position="Engineer" />