Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you show an example of passing data to a Blade component
    Laravel Blade components data passing PHP web development Laravel tutorial


Can you show an example of passing data to a Blade component


Here is an example of passing data to a Laravel Blade component:

Let's say we have a `` component that displays an alert message with a specified type. We can pass the `type` and `message` data to the component like this:

html
<x-alert type="error" :message="$errorMessage" />

In the `AlertComponent.php` class, we define the necessary data in the constructor:

php
class AlertComponent extends Component
{
    public function __construct(
        public string $type,
        public string $message
    ) {}

    public function render(): View
    {
        return view('components.alert');
    }
}

The `alert.blade.php` view file can then display the data:

html
<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>

The `type` attribute is passed as a string, while the `message` attribute uses the `:` prefix to pass a variable from the parent view[1][4].

This allows you to reuse the `` component throughout your application and pass in the necessary data each time[2].

Citations:
[1] https://www.fundaofwebit.com/post/laravel-blade-components-tutorial-with-example-all-about-components-in-laravel
[2] https://www.youtube.com/watch?v=EmdSTA2znTg
[3] https://www.reddit.com/r/laravel/comments/pjio7g/passing_data_between_blade_components/
[4] https://stackoverflow.com/questions/71435335/passing-php-variable-to-laravel-blade-component
[5] https://laravel.com/docs/11.x/blade