Search code examples
phpjquerylaravellaravel-livewirelaravel-9

edit user data user data using livewire component from controller


I want to pass the id from the standard blade view to the livewire component view.

I have an edit user button in the blade file, so when the user clicks on the button bootstrap modal (which is a livewire component view) with id will open.

//some ajax to render the table with an edit button

success: function(response) {                   
    $('tbody').html("");
    $.each(response, function(key, item) {
    str += '<tr>';
    //blahh...
    str += '<a href="#" id="' + item.id + '" wire:click="edit({{ '+item.id+' }})" class="text-info mx-1 editIcon" data-toggle="modal" data-target="#editUserModal"></a>';
    //blahh...
    str += '</tr>';
    })
    $('tbody').append(str);
)};

if I stick to jquery I can successfully open a modal with data to edit. but I want to open the modal as a livewire component.

livewire view

<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-hidden="true">
    //blahh
</div>

livewire component

public function render()
{
    //some logic here to open modal with id clicked, so I can do something as below
    $user = User::where('id', $id)->first();        
    
    $this->user_id = $id;
    $this->first_name = $student->student_first_name;
    return view('livewire.user.edit');
}

any suggestion will be helpful. I don't want to port the whole project to livewire I just want to use the livewire component for some places due to its simplicity and lesser code


Solution

  • You can emit an event from the table click using $emit or Livewire.emit.

    success: function(response) {                   
        $('tbody').html("");
        $.each(response, function(key, item) {
        str += '<tr>';
        //blahh...
        str += '<a href="#" id="' + item.id + '" wire:click="$emit({{ openmodal'+item.id+' }})" class="text-info mx-1 editIcon" data-toggle="modal" data-target="#editUserModal"></a>';
        //blahh...
        str += '</tr>';
        })
        $('tbody').append(str);
    )};
    

    And listen on your modal:

    public bool $open = false;
    
    public ?int $userId = null;
    
    protected $listeners = ['openmodal' => 'openModal'];
    
    public openModal(int $userId)
    {
        $this->userId = $userId;
        // you can load your user data here
        $user = User::findOrFail($userId);
    }
    
    public function render()
    {
        return view('livewire.user.edit');
    }