How to Create Reusable Components in Laravel Any Version?
Laravel

How to Create Reusable Components in Laravel Any Version?

In this tutorial, I would you to show, how to create reusable components in laravel using components and slots.

Laravel provides blade components for creating components and slots. You can easily create components in laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9. Let's start with an example

 

First, create blade components like as below

resources/views/components/card.blade.php

<div class="widget {{ $class }}">
    <h5 class="widget-header">{{ $title }}</h5>
    <div class="widget-body">
       <p class="widget-text">{{ $slot }}</p>
    </div>
</div>

 

Now we need to create a route and blade file for using this component. Follow us below

routes/web.php

Route::get('widget-components', function () {

    return view('widget-component');

});

//or
Route::view('widget-components', 'widget-component');

resources/views/widget-component

<!DOCTYPE html>
<html>
<head>
    <title>Topics - Kodersolution.Com</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>Topics</h3>
   
    <!-- For Primary -->
    @component('components.card')    
   
        @slot('class')
            bg-primary
        @endslot
  
        @slot('title')
            This is from Kodersolution.com(Primary)
        @endslot
  
        My custom widget component with primary background
    @endcomponent
  
    <br/>
  
    <!-- For Success -->
    @component('components.card')    
   
        @slot('class')
            bg-success
        @endslot
  
        @slot('title')
            This is from Kodersolution.com(Success)
        @endslot
  
        My custom widget component with success background
    @endcomponent
  
    <br/>
  
   
    <!-- For Info -->
    @component('components.card')    
   
        @slot('class')
            bg-primary
        @endslot
  
        @slot('title')
            This is from Kodersolution.com(Info)
        @endslot
  
        My custom widget component with info background
    @endcomponent
    
  
</div>
  
</body>
</html>

 

I hope, it will help you to create reusable components.

Get The latest Coding solutions.

Subscribe to the Email Newsletter