Laravel 10 How to Create Reusable Component in Laravel

Hello artisan, today I'll show you how to create reusable components that can be used thoroughly in our Laravel application. So, let's get dive into the topic.

Table of Contents

  1. Setup View
  2. Setup Route
  3. Output

Setup View

At first, we'll create a blade file called card.blade.php, and this blade we'll used as a component. That means whenever we need to use any card for primary, success, or for danger then we'll just use this card. So, look at the below source code.

resources/views/card.blade.php
<div class="card {{ $class }}">
    <h5 class="card-header">{{ $title }}</h5>
    <div class="card-body">
        <p class="card-text">{{ $slot }}</p>
    </div>
</div>

Here we'll create a card and let the class title and body will be dynamic. That means whenever we're going to extend this component, then we'll use this value according to our needs.

Now, we'll use the above component. Let's create a new file called my_components.blade.php, where we'll use the different types of cards as our goal is to create and use reusable cards. Let's see the below source code.

resources/views/my_components.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>How to create reusable blade components in Laravel 10 - shouts.dev</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css" />
</head>
<body>
<div class="container">
    <h3>How to create reusable blade components in Laravel 10 - shouts.dev</h3>

    <!-- For Primary -->
    @component('card')

        @slot('class')
            bg-primary
        @endslot

        @slot('title')
            This is from shouts.dev(Primary)
        @endslot

        My components with primary
    @endcomponent
    <br/>

    <!-- For Danger -->
    @component('card')

        @slot('class')
            bg-danger
        @endslot

        @slot('title')
            This is from shouts.dev(Danger)
        @endslot

        My components with primary
    @endcomponent
    <br/>

    <!-- For Success -->
    @component('card')

        @slot('class')
            bg-success
        @endslot

        @slot('title')
            This is from shouts.dev(Success)
        @endslot

        My components with primary
    @endcomponent
</div>
</body>
</html>

And like these, we can use it in any blade file as a component.

Setup Route

Put the below route in the web.php file.

routes/web.php
Route::get('my-components', function () {
    return view('my_components');
});

Output

Now it's the time to check the output. Go to localhost:8000/my-components, and you'll find the below output

That's it for today. I hope it'll be helpful in the upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚