To conditionally render Blade components in Laravel views, you can use the @if
directive. Here's how you can do it:
make:component
Artisan command:php artisan make:component MyComponent
This will create a new Blade component class in the app/View/Components
directory.
// app/View/Components/MyComponent.php
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class MyComponent extends Component
{
public $condition;
public function __construct($condition)
{
$this->condition = $condition;
}
public function render()
{
return view('components.my-component');
}
}
resources/views/components
directory:<!-- resources/views/components/my-component.blade.php -->
<div>
<!-- Component markup here -->
</div>
@if
directive to conditionally render the component:@if($someCondition)
<x-my-component :condition="$someCondition" />
@endif
Replace $someCondition
with the actual condition you want to test. If the condition is true, the component will be rendered; otherwise, it will be skipped.
That's it! The Blade component will be conditionally rendered based on the specified condition in the view.