Reputation: 75
I have a function that let a user to upload and save the file to the system and show the file in the table. The problem is whenever there is a duplicate name it will not appear in the database and the file will not show in the table. As the title says, how to give uniqid/hash value to saved file?
Here is my code:
public function updatepekerjaan(Request $request, $id){
$pekerjaan = Pekerjaan::find($id);
$pekerjaan->update($request->all());
if($request->hasFile('gambar')){
$request->file('gambar')->move('gambarpekerjaan/', $request->file('gambar')->getClientOriginalName());
$pekerjaan->gambar = $request->file('gambar')->getClientOriginalName();
$pekerjaan->save();
// $file = request()->file('gambar');
// $extension = $file->getClientOriginalName();
// $destination = 'gambarpekerjaan/';
// $filename = uniqid() . '.' . $extension;
// $file->move($destination, $filename);
// $new_file = new Pekerjaan();
// $new_file->gambar = $filename;
// $new_file->save(); << doesn't work
}
return redirect()->route('datapekerjaan')->with('message','Pekerjaan Berhasil diupdate!');
}
I have also tried changing the getClientOriginalName into hashName but it doesn't work
$pekerjaan->update($request->all());
if($request->hasFile('gambar')){
$request->file('gambar')->move('gambarpekerjaan/', $request->file('gambar')->hashName());
$pekerjaan->gambar = $request->file('gambar')->hashName();
$pekerjaan->save();
Upvotes: 0
Views: 161
Reputation: 101
You can use the timestamp to generate unique filename
if($request->hasFile('gambar')){
$fileExtension = $request->file('gambar')->getClientOriginalExtension();
$basename = uniqid(time());
$filename = $basename.'.'.$fileExtension;
$request->file('gambar')->move('gambarpekerjaan/', $filename);
$pekerjaan->gambar = $filename;
$pekerjaan->save();
Upvotes: 1