Skip to content

Instantly share code, notes, and snippets.

@ulmaull
Last active November 21, 2019 04:18
Show Gist options
  • Save ulmaull/d9cdbabc39ce464412d9d1fdb8dcb9de to your computer and use it in GitHub Desktop.
Save ulmaull/d9cdbabc39ce464412d9d1fdb8dcb9de to your computer and use it in GitHub Desktop.
private function saveFile($name, $photo)
{
//set nama file adalah gabungan antara nama produk dan time(). Ekstensi gambar tetap dipertahankan
$images = str_slug($name) . time() . '.' . $photo->getClientOriginalExtension();
//set path untuk menyimpan gambar
$path = public_path('uploads/product');
//cek jika uploads/product bukan direktori / folder
if (!File::isDirectory($path)) {
//maka folder tersebut dibuat
File::makeDirectory($path, 0777, true, true);
}
//simpan gambar yang diuplaod ke folrder uploads/produk
Image::make($photo)->save($path . '/' . $images);
//mengembalikan nama file yang ditampung divariable $images
return $images;
}
public function store(Request $request)
{
//validasi data
$this->validate($request, [
'code' => 'required|string|max:10|unique:products',
'name' => 'required|string|max:100',
'description' => 'nullable|string|max:100',
'stock' => 'required|integer',
'price' => 'required|integer',
'category_id' => 'required|exists:categories,id',
'photo' => 'nullable|image|mimes:jpg,png,jpeg'
]);
try {
//default $photo = null
$photo = null;
//jika terdapat file (Foto / Gambar) yang dikirim
if ($request->hasFile('photo')) {
//maka menjalankan method saveFile()
$photo = $this->saveFile($request->name, $request->file('photo'));
}
//Simpan data ke dalam table products
$product = Product::create([
'code' => $request->code,
'name' => $request->name,
'description' => $request->description,
'stock' => $request->stock,
'price' => $request->price,
'category_id' => $request->category_id,
'photo' => $photo
]);
//jika berhasil direct ke produk.index
return redirect(route('produk.index'))
->with(['success' => '<strong>' . $product->name . '</strong> Ditambahkan']);
} catch (\Exception $e) {
//jika gagal, kembali ke halaman sebelumnya kemudian tampilkan error
return redirect()->back()
->with(['error' => $e->getMessage()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment