Search code examples
phplaravelvalidationfile-uploadlaravel-livewire

Laravel / Livewire: Ignore "image" rule when updating


Simply put, i have to update the user.

This is my validation rule for the image:

protected $rules = [
    //other rules
    "profile_image" => "sometimes|image|max:1024",
];

Mount method:

public function mount($user)
{
    //other
    $this->profile_image = $user->profile_image;
} 

The validation rules work as expected, but the problem is i store the image into the database as a string: example of how it looks profile_image: "public/images/tprYt36hk0Ztun9yKBYpUGEX3TJuAaBWMi5bSkTZ.jpg"

This means that when i want to update the user without changing the profile image, i can't because of the image validation rule, i can only pass when an image is selected.

This is how my update method looks:

public function updateCook()
{
    $this->validate();
    try {

        $image = $this->profile_image->store("public/images");

        $this->user->update([
            //other updates
            "profile_image" => $image,
        ]);

        session()->flash('success', 'User is updated');

    } catch (\Exception $e) {
        session()->flash('error', 'An error occured');
    }
}

If i remove the image validation rule and try submitting the form without uploading a new image i get Call to a member function store() on string.


Solution

  • I have found an answer:

    protected $rules = [
        "profile_image" => "nullable|image|max:1024",
    ];
    

    Then as @Khan Tran said i simply removed $this->profile_image = $user->profile_image; in the mount() method

    In my updateCook() method i did this:

    public function updateCook()
    {
        $this->validate();
        try {
            if ($this->profile_image) {
                $image = $this->profile_image->store("public/images");
                $this->user->update([
                    // + other updates
                    "profile_image" => $image,
                    
                ]);
            } else {
                // No new image is uploaded, update other fields only
                $this->user->update([
                    //Oter updates
                ]);
            }
    
            session()->flash('success', 'User is updated');      
    
        } catch (\Exception $e) {
            session()->flash('error', 'Грешка при ажурирањето на корисникот.');
        }
    }