In Laravel, you can pass data to Blade components using the with
method. This method is used to bind data to a component instance, allowing you to access it within the component's template.
Here's how you can pass data to a Blade component:
Create a Blade component using the php artisan make:component
command. For example, if you want to create a component called "Alert", run php artisan make:component Alert
.
In your component's class, define a public property to hold the data you want to pass to the component.
// app/View/Components/Alert.php
public $message;
public function __construct($message)
{
$this->message = $message;
}
<!-- resources/views/components/alert.blade.php -->
<div class="alert">
{{ $message }}
</div>
<x>
prefix followed by the name of your component, and then call the with
method, passing the desired data as an argument.<!-- resources/views/welcome.blade.php -->
<x-alert with="Hello, World!" />
In this example, the "Hello, World!" message will be passed to the Alert
component and displayed within the specified template. You can customize the data being passed to the component by modifying the with
method argument.
Additionally, you can further customize the behavior of Blade components by passing additional attributes and properties. You can access these attributes and properties within the component's class or view file.