96 lines
2.8 KiB
PHP
96 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Pengumuman;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class PengumumanController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$pengumumans = Pengumuman::latest()->get();
|
|
return view('pengumuman.index', compact('pengumumans'));
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
return view('pengumuman.create');
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$request->validate([
|
|
'judul' => 'required|string|max:255',
|
|
'deskripsi' => 'nullable|string',
|
|
'foto' => 'required|image|mimes:jpeg,png,jpg|max:2048',
|
|
'status' => 'required|in:aktif,nonaktif'
|
|
]);
|
|
|
|
// Proses upload foto
|
|
$fotoPath = $request->file('foto')->store('pengumuman', 'public');
|
|
|
|
Pengumuman::create([
|
|
'judul' => $request->judul,
|
|
'deskripsi' => $request->deskripsi,
|
|
'foto' => $fotoPath,
|
|
'status' => $request->status,
|
|
]);
|
|
|
|
return redirect()->route('pengumuman.index')->with('success', 'Data pengumuman berhasil ditambahkan!');
|
|
}
|
|
|
|
public function edit($id)
|
|
{
|
|
$pengumuman = Pengumuman::findOrFail($id);
|
|
return view('pengumuman.edit', compact('pengumuman'));
|
|
}
|
|
|
|
public function update(Request $request, $id)
|
|
{
|
|
$pengumuman = Pengumuman::findOrFail($id);
|
|
|
|
$request->validate([
|
|
'judul' => 'required|string|max:255',
|
|
'deskripsi' => 'nullable|string',
|
|
'foto' => 'nullable|image|mimes:jpeg,png,jpg|max:2048', // Nullable karena foto tidak harus diganti
|
|
'status' => 'required|in:aktif,nonaktif'
|
|
]);
|
|
|
|
$data = [
|
|
'judul' => $request->judul,
|
|
'deskripsi' => $request->deskripsi,
|
|
'status' => $request->status,
|
|
];
|
|
|
|
// Jika user mengunggah foto baru
|
|
if ($request->hasFile('foto')) {
|
|
// Hapus foto lama
|
|
if (Storage::disk('public')->exists($pengumuman->foto)) {
|
|
Storage::disk('public')->delete($pengumuman->foto);
|
|
}
|
|
// Simpan foto baru
|
|
$data['foto'] = $request->file('foto')->store('pengumuman', 'public');
|
|
}
|
|
|
|
$pengumuman->update($data);
|
|
|
|
return redirect()->route('pengumuman.index')->with('success', 'Data pengumuman berhasil diperbarui!');
|
|
}
|
|
|
|
public function destroy($id)
|
|
{
|
|
$pengumuman = Pengumuman::findOrFail($id);
|
|
|
|
// Hapus foto dari storage
|
|
if (Storage::disk('public')->exists($pengumuman->foto)) {
|
|
Storage::disk('public')->delete($pengumuman->foto);
|
|
}
|
|
|
|
$pengumuman->delete();
|
|
|
|
return redirect()->route('pengumuman.index')->with('success', 'Pengumuman berhasil dihapus!');
|
|
}
|
|
}
|