Search code examples
laravellaravel-livewire

Passing data from laravel controller to livewire component class


I just started using livewire recently so please bear with me.
I currently have a controller that handles a bunch of queries.
It has a variable called $roomTypes, which an array of RoomType models.
I'm trying to send that to a livewire component class, which renders the full-page component and displays the room types.
How can I accomplish this? I've searched other stackoverflow questions and tried chatgpt answers, but so far nothing has been fruitful.

Note: The reason I need to pass the data to the class, instead of returning the view directly, is because I have another livewire select component that has options to sort the room types and update them in real time.
Thanks in advance! Also if you suggestions on a better way to structure this, please don't hesitate.


Solution

  • if you need only one part of you page to be "live" then it is okay to use component and provide to it data from controller. But if you are planning to use livewire in most of the page then rather create full-page component.

    If you want to provide data from controller to the livewire you need to do few steps:

    1. Get data from controller
    $myData = MyModel::all();
    return view('some.view' , [
       'myData' => $myData
    ]);
    
    1. In your "some.view" blade file you need to load livewire component
    php artisan livewire:make MyDataComponent
    
    and in your blade file do this
    
    <livewire:my-data-component></livewire:my-data-component>
    
    Your data is still not provided so do this
    <livewire:my-data-component :myData="$myData"></livewire:my-data-component>
    
    This way you are telling component - My blade file has some data I'd like you to take and handle it.
    
    1. Now go to your MyDataComponent.php and put this
    public $myData;
    
    public function mount($myData) {
        $this->myData = $myData;
    }
    

    And that is basically it. You can now go to your my-data-component and @dd($myData)

    NOTE: Your livewire blade component always must have 1 wrapper element for example

    everything goes inside
    @dd($myData)

    Enjoy :)