TIF_NGANJUK_E41220949/app/Http/Controllers/Admin/PengumumanController.php

83 lines
3.0 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pengumuman;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
class PengumumanController extends Controller
{
public function index()
{
$pengumuman = Pengumuman::orderBy('tanggal_pengumuman', 'desc')->get();
return view('admin.pengumuman.index', compact('pengumuman'));
}
public function create()
{
return view('admin.pengumuman.create');
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'judul_pengumuman' => 'required|string|max:255',
'isi_pengumuman' => 'required|string',
'tanggal_pengumuman' => 'required|date',
'gambar_pengumuman' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
if ($validator->fails()) return redirect()->back()->withErrors($validator)->withInput();
$data = $request->only('judul_pengumuman','isi_pengumuman','tanggal_pengumuman');
if ($request->hasFile('gambar_pengumuman')) {
$data['gambar_pengumuman'] = $request->file('gambar_pengumuman')->store('pengumuman', 'public');
}
Pengumuman::create($data);
return redirect()->route('admin.pengumuman.index')->with('success','Pengumuman berhasil ditambahkan.');
}
public function edit($id_pengumuman)
{
$pengumuman = Pengumuman::findOrFail($id_pengumuman);
return view('admin.pengumuman.edit', compact('pengumuman'));
}
public function update(Request $request, $id_pengumuman)
{
$pengumuman = Pengumuman::findOrFail($id_pengumuman);
$validator = Validator::make($request->all(), [
'judul_pengumuman' => 'required|string|max:255',
'isi_pengumuman' => 'required|string',
'tanggal_pengumuman' => 'required|date',
'gambar_pengumuman' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
if ($validator->fails()) return redirect()->back()->withErrors($validator)->withInput();
$data = $request->only('judul_pengumuman','isi_pengumuman','tanggal_pengumuman');
if ($request->hasFile('gambar_pengumuman')) {
if ($pengumuman->gambar_pengumuman) Storage::disk('public')->delete($pengumuman->gambar_pengumuman);
$data['gambar_pengumuman'] = $request->file('gambar_pengumuman')->store('pengumuman','public');
}
$pengumuman->update($data);
return redirect()->route('admin.pengumuman.index')->with('success','Pengumuman berhasil diperbarui.');
}
public function destroy($id_pengumuman)
{
$pengumuman = Pengumuman::findOrFail($id_pengumuman);
if ($pengumuman->gambar_pengumuman) Storage::disk('public')->delete($pengumuman->gambar_pengumuman);
$pengumuman->delete();
return redirect()->route('admin.pengumuman.index')->with('success','Pengumuman berhasil dihapus.');
}
}