<?php
namespace App\Http\Controllers;
use App\Models\artikel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class ArtikelController extends Controller
{
public function index()
{
$datas = artikel::get();
return response()->view('artikel.index', ['datas' => $datas]);
}
public function edit($id)
{
$datas = artikel::find($id);
return response()->view('artikel.edit', ['data' => $datas]);
}
public function create()
{
return response()->view('artikel.create');
}
public function store(Request $request)
{
$request->validate([
'photo' => 'required|image|mimes:jpeg,png,jpg,gif|max:2000',
'title' => 'required',
'deskripsi' => 'required',
]);
DB::beginTransaction();
try {
$datas = [
'title' => $request->title,
'author' => auth()->user()->nama_pengguna,
'deskripsi' => $request->deskripsi,
'tag' => $request->tag,
];
if ($request->hasFile('photo')) {
$photo_file = $request->file('photo');
$photo_ekstensi = $photo_file->extension();
$photo_baru = "photo-" . date('ymdhis') . ".$photo_ekstensi";
$photo_file->move(public_path('images/artikel'), $photo_baru);
$data['photo'] = $photo_baru;
} else {
return redirect()->route('profil.index')->with('error', "Masukan Foto terlebih dahulu!");
}
artikel::create($data);
DB::commit();
return redirect()->route('artikel.index')->with('success', 'Foto artikel berhasil di tambahkan.');
} catch (\Throwable $th) {
DB::rollback();
return redirect()->route('artikel.index')->with('error', $th->getMessage());
}
}
public function update(Request $request, $id)
{
$request->validate([
'photo' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
DB::beginTransaction();
try {
$artikel = artikel::find($id);
if ($request->hasFile('photo')) {
$photo_file = $request->file('photo');
$photo_ekstensi = $photo_file->extension();
$photo_baru = "photo-" . date('ymdhis') . ".$photo_ekstensi";
$photo_file->move(public_path('images/artikel'), $photo_baru);
$data['photo'] = $photo_baru;
$photo_lama = $artikel->photo;
File::delete(public_path('images/artikel') . "/" . $photo_lama);
} else {
return redirect()->route('artikel.index')->with('error', "Masukan Foto terlebih dahulu!");
}
$artikel->update($data);
DB::commit();
return redirect()->route('artikel.index')->with('success', 'Profil berhasil diubah');
} catch (\Throwable $th) {
DB::rollback();
return redirect()->route('artikel.index')->with('error', $th->getMessage());
}
}
public function destroy(artikel $artikel)
{
DB::beginTransaction();
try {
$photo_lama = $artikel->photo;
File::delete(public_path('images/artikel') . "/" . $photo_lama);
$artikel->delete();
DB::commit();
return redirect()->route('artikel.index')->with('success', 'artikel berhasil dihapus');
} catch (\Throwable $th) {
DB::rollback();
return redirect()->route('artikel.index')->with('error', 'Item gagal dihapus');
}
}
}
Anons79 File Manager Version 1.0, Coded By Anons79
Email: [email protected]