Reusable components are modular, self-contained Livewire components that can be used across multiple parts of your application. They follow the DRY (Don’t Repeat Yourself) principle, making your codebase more maintainable and scalable.
Let’s start by building a reusable Alert Component that displays success, warning, or error messages.
Run the following command to create the component:
php artisan make:livewire Alert
This will generate:
app/Livewire/Alert.php
– The PHP class for the component.
resources/views/livewire/alert.blade.php
– The Blade view for the component.
Open Alert.php
and update the logic to accept dynamic properties:
In alert.blade.php
, design the alert message UI with dynamic classes:
@if($message)
{{ $message }}
@endif
You can use the alert component anywhere in your Blade templates:
Pagination is a common feature in most applications. Let’s build a reusable pagination component.
php artisan make:livewire Pagination
Open Pagination.php
and add the logic for handling paginated data:
model::paginate(10);
return view('livewire.pagination', [
'items' => $items,
]);
}
}
In pagination.blade.php
, display the paginated items:
@foreach ($items as $item)
- {{ $item->name }}
@endforeach
{{ $items->links() }}
To use the pagination component, pass the model dynamically:
Use public properties to pass data dynamically into components:
public $title;
public $subtitle;
Blade slots allow you to inject dynamic content into components:
{{ $title }}
{{ $slot }}
Use the component
This is the dashboard content.
Extend components for shared functionality:
class BaseComponent extends Component
{
public function log($message)
{
// Shared logic
}
}
Inherit in child components:
class ChildComponent extends BaseComponent
{
public function someMethod()
{
$this->log('Message logged from child component.');
}
}
If you have repeated code across components, refactor them into reusable components or traits.
Create a simple button component:
php artisan make:livewire Button
Blade View:
Use it anywhere:
Submit
Cancel
By building reusable components, you can:
Save time and effort by reusing existing functionality.
Maintain consistency across your application.
Reduce redundancy and make your codebase more maintainable.
Creating reusable components like alerts, pagination, and buttons.
Passing dynamic properties to Livewire components.
Using Blade slots for flexible content injection.
Best practices for refactoring and modularizing your code.
410 C, Jaina Tower-1, District Center, Janak Puri New Delhi-110058, India.
© Copyright 2025 Wontonee. All Right Reserved.