Search code examples
laravellaravel-livewire

Livewire: how to grab ID of newly created row?


I created a button with livewire, that when it is clicked. It will generate a new Kanban board in the database.

enter image description here

<div>
    <form>
        <button wire:click="addKanban" class="h-8 w-8 rounded bg-blueGray-100  text-lg text-gray-900 focus:outline-none hover:text-white hover:bg-blue-500 ">
            <i class="bi bi-plus"></i>
        </button>
    </form>
</div>

In the livewire php file this is the function

public function addKanban ()
    {
        $record = $this->validate([
            'team_id' => 'required',
            'icon' => 'required',
            'color' => 'required',
            'title' => 'required',
            'order' => 'required',
            'status' => 'required'
        ]);

        Kanban::create($record);

        $this->resetInputFields();
        
        return redirect()->route('kanbans.show-all',['kanban'=>$this->$kanban->id]);
    }

Once it creates the row in the database, I would want it to redirect to a page that would display that kanban. I found this documentation on how to do it https://laravel.com/docs/8.x/redirects , but I can't seem to get the new kanban id

This is supposed to be like return redirect()->route('kanbans.show-all',['kanban'=>'new kanban id']);

The closest I got was doing ['kanban'=>$this->id] however, this returns the randomized string ID that livewire creates and it goes to team/kanban/a69J5LmObUjcKbmJYPxE/show-all instead of team/kanban/1/show-all

Any help or insight much appreciated :)


Solution

  • public function addKanban ()
    {
            $record = $this->validate([
                'team_id' => 'required',
                'icon' => 'required',
                'color' => 'required',
                'title' => 'required',
                'order' => 'required',
                'status' => 'required'
            ]);
    
            $modelCreated = Kanban::create($record);
    
            $this->resetInputFields();
            
            return redirect()->route('kanbans.show-all',['kanban'=>$modelCreated->id]);
        }
    

    that's all, remember manage correctly this through the route model binding way, hope this help you