Laravel 5.4 replace file if exists
I need to resolve a small inconvenience I present when updating an image when the associated registry changes.
When I change the registry, I want to replace the associated file that is in the directory.
This is my table structure:
Schema::create('institutions', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name')->unique();
$table->string('initials')->nullable();
$table->string('description')->nullable();
$table->string('avatar')->default('default.jpg');
$table->timestamps();
});
This is my update method on my controller:
public function update(Request $request, $id)
{
//
$institution = $this->institution->find($id);
try
{
$institution->update($request->all());
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(250, 205)->save( public_path('uploads/institutions/' . $filename ) );
$institution->avatar = $filename;
$institution->save();
}
$updated = $institution;
$message = flash('Institución actualizada correctamente!!!', 'success');
return redirect()->route('instituciones.index')->with('message', $message);
}
catch(\Illuminate\Database\QueryException $e)
{
$message = flash('La institución no se actualizó correctamente!!!', 'danger');
return redirect()->route('institutions.create')->with('message', $message);
}
}
I tried different methods, but I didn't succeed.
+3
source to share
1 answer
The uploaded image must have the same filename in order to replace the old one, but in this case it will not replace due to the method time()
.
You can delete the old one by getting the filename from the database and save the new image
//find data by id
$institution = $this->institution->find($id);
$filename = public_path('uploads/institutions/').$institution->avatar;
if(File::exists($filename)) {
$avatar = $request->file('avatar');
$filename_new = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(250, 205)->save( public_path('uploads/institutions/' . $filename_new ) );
//update filename to database
$institution->avatar = $filename_new;
$institution->save();
//Found existing file then delete
File::delete($filename); // or unlink($filename);
}
Hope it helps
+3
source to share