Passing data to a component is a common thing to do. Let's see how we can do that.
When rendering a Livewire component, we can pass a value to a property.
<livewire:create-post title="This is a title" />
Here we pass the initial title to the CreatePost
Livewire component. We need to accept this in the components mount
lifecycle hook.
class CreatePost extends Component{ public string $title = ''; public function mount(string $title = null): void { $this->title = $title; } // ...}
The mount
method in Livewire is identical to the __construct
used in PHP classes.
If you need to pass dynamic values or variables to a component, you can write PHP expressions in component attributes by prefixing the attribute with a colon:
<livewire:create-post :title="$initialTitle" />
Also, in the Livewire components, you can use the request
helper. For example, in the URL, if you have some parameter, let's say ?post_id
, then in the component you would do the:
use App\Models\Post; class CreatePost extends Component{ public Post $post; public function mount(): void { $this->post = Post::find(request('post_id')); } // ...}
Or, if needed, you can use Route Model Binding, especially if using Full Page Components.
The Route could be something like this:
Route::get('post/{post}', \App\Livewire\EditPost::class);
Then in the Livewire component, the mount
method would be:
use App\Models\Post; class EditPost extends Component{ public Post $post; public function mount(Post $post): void { $this->post = $post; } // ...}