Actualizar el método de perfil en Laravel
//web.php
Route::post('update-profile',[App\Http\Controllers\HomeController::class,'updateProfile'])->name('update-profile');
//_controller.php
public function __construct()
{
$this->middleware('auth');
}
public function updateProfile(Request $request){
$request->validate([
"name" => "required|min:3|max:50",
"photo" => "nullable|file|mimes:jpeg,png|max:1000",
]);
$user = User::find(auth()->id());
$user->name = $request->name;
if($request->hasFile('photo')){
// delete old photo => path:storage/profile/profile_6221cecf36ad9.jpg
$subStrPhotoName = Str::substr($user->photo,16);
Storage::delete('public/profile/'.$subStrPhotoName);
// create new photo
$dir="storage/profile";
$newName = "profile_".uniqid().".".$request->file('photo')->extension();
$request->file('photo')->storeAs("public/profile",$newName);
$user->photo = $dir."/".$newName;
}
$user->update();
return redirect()->back();
}
//update.blade.php
<form action="{{ route('update-profile') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="">
<input type="file" name="photo" accept="image/jpeg,image/png" value="{{ old('photo',auth()->user()->photo) }}" class="@error('photo') is-invalid @enderror">
@error('photo')
<div class="invalid-feedback ps-2">{{ $message }}</div>
@enderror
</div>
<div class="form-floating mb-3">
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror" id="yourName" value="{{ auth()->user()->name }}" placeholder="[email protected]">
<label for="yourName">Your Name</label>
@error('name')
<div class="invalid-feedback ps-2">{{ $message }}</div>
@enderror
</div>
<div class="form-floating mb-3">
<input disabled type="email" class="form-control" id="yourEmail" value="{{ auth()->user()->email }}" placeholder="[email protected]">
<label for="yourEmail">Your Email</label>
</div>
<div class="text-center">
<button class="btn btn-lg btn-primary text-white">Update Profile</button>
</div>
</form>
WinMaw