'How update and unlink image from image folder using livewire?
I'm use this controller for trying to unlink my images from folder and database. It is successfully being deleted from database. But I can't unlink images from my folder
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\User as TableUser;
use Illuminate\Support\Facades\Hash;
use Livewire\WithFileUploads;
class User extends Component
{
use WithFileUploads;
public $ids;
public $user;
public $name;
public $email;
public $password;
public $photo;
public $photoOld;
public function detail($id)
{
$user = TableUser::where('id', $id)->first();
$this->ids = $user->id;
$this->name = $user->name;
$this->email = $user->email;
$this->password = $user->password;
$this->photoOld = $user->photo;
}
public function update()
{
$this->validate([
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required',
'photo' => 'required|image|max:1024',
]);
if ($this->ids) {
$photo = $this->photo->store('photos', 'public');
if (preg_match('/photos/', $this->photo)) {
unlink(public_path('photos/' . $this->photo));
}
} else {
$photo = $this->photoOld;
}
$data = TableUser::find($this->ids);
$data->update([
'name' => $this->name,
'email' => $this->email,
'password' => Hash::make($this->password),
'photo' => $photo,
]);
$this->resetform();
$this->emit('closemodaledit');
}
}
Solution 1:[1]
try this
protected function rules()
{
return [
'name' => ['required', 'string', 'max:50', 'min:5'],
'email' => ['required', 'string', 'email', 'max:60', 'unique:users,email,' . $this->modelId,],
'password' => ['nullable', 'string', 'min:8', 'confirmed'], // if you not have password confirmed remove (confirmed)
'photo' => 'nullable|image|mimes:jpeg,png,jpg|max:650',
];
}
public function updatedPhoto()
{
$this->validate([
'photo' => 'image|mimes:jpeg,png,jpg|max:1024',
]);
}
public function update()
{
if ($this->validate()) {
$data = [
'name' => $this->name,
'username' => $this->username,
'email' => $this->email,
];
if (!empty($this->password)) {
$validatedData = $this->validate([
'password' => 'required|string|min:8|confirmed',
]);
$data['password'] = Hash::make($validatedData['password']);
}
if (!empty($this->photo)) {
$namePhoto = $this->avatar->store('photos', 'public');
$data['photo'] = $namePhoto;
} else {
$data['photo'] = $this->photoOld;
}
$user = TableUser::where('id', $this->ids)->update($data);
}
$this->resetform();
$this->emit('closemodaledit');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abdulmajeed |
