Search code examples
laravellaravel-livewire

Laravel Livewire model property binding


This is my Livewire component

<?php

namespace App\Http\Livewire\Dashboard;

use App\Models\Post;
use Livewire\Component;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class EditPost extends Component
{
    use AuthorizesRequests;

    public ?Post $postSingle = null;

    protected $rules = [
        'postSingle.priority' => 'digits_between:1,5',
    ];

    public function setPriority(Post $postSingle, $priority)
    {
        $this->authorize('update', $postSingle);
        $this->postSingle->priority = $priority;
    }

}

In my blade view I have <button wire:click="setPriority({{ $postSingle->id }}, 4)"></button>

and somewhere else I show the priority with {{ $postSingle->priority }}

The reason why I don't do model property binding directly with wire:model="postSingle.priority" is that I want to run $this->authorize('update', $postSingle);.

What happens with the code below is that if I click the button, $postSingle->priority in the blade view is updated, but the Post record is not updated in my database. What am I missing?


Solution

  • You appear to have overlooked actually saving the record.

    public function setPriority(Post $postSingle, $priority)
    {
        $this->authorize('update', $postSingle);
        $this->postSingle->priority = $priority;
    
        // save the record
        $this->postSingle->save();
    }