Search code examples
laraveldatatablelaravel-livewire

Laravel livewire passing data between two components not in the same page


I'm using Laravel and Livewire for the first time, so apologize if the question is silly.

I've read from Livewire documentation https://laravel-livewire.com/docs/2.x/events that

Livewire components can communicate with each other through a global event system. As long as two Livewire components are living on the same page, they can communicate using events and listeners.

I have two datatables that need to comunicate, but they're not on the same page.

Is there a possible workaround or solution? Many thanks.


Solution

  • Route model binding is the answer to that. If you load in one component, for example from a row of User table the id, you can redirect to another component binding the id through the route. User Table blade

    <td>
      <a href="{{ route('user.activity', ['id' => $user->id]) }}">View Activity</a>
    <td>
    

    web.php

    Route::get('activity/user/{id}', UserActivityComponent::class)->name('user.activity');
    

    UserActivityComponent it's going to be rendered once you make click or access it through tag (in my example case). So, like docs said, you can do this

    class UserActivityComponent extends Component
    {
      public $user;
    
      public $name;
      public $email;
      
      //....
      public function mount($id)
      {
         $this->user = User::find($id);
         $this->name = $this->user->name;
         $this->email = $this->user->email;
      }
      public function render()
      {
         return view('user-activity-component');
      }  
    }
    

    and deploy in the UserActivityComponent blade all that you want to show in this