How to Create Reusable Components in Laravel Any Version?

Avatar
C

Callum Davies

Senior Backend Engineer••
7923Views
5mRead
0Reactions

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.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?

Recommended Resources & Courses

Partner Links
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article