MIF_E31221305/TA_website/app/Http/Controllers/Admin/CustomerController.php

114 lines
3.1 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class CustomerController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$customers = User::where('role', 'pelanggan')->latest()->paginate(10);
return view('admin.customers.index', compact('customers'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('admin.customers.create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|string|max:15',
'address' => 'required|string',
]);
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone' => $request->phone,
'address' => $request->address,
'role' => 'pelanggan',
]);
return redirect()->route('admin.customers.index')
->with('success', 'Pelanggan berhasil ditambahkan');
}
/**
* Display the specified resource.
*/
public function show(User $customer)
{
return view('admin.customers.show', compact('customer'));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(User $customer)
{
return view('admin.customers.edit', compact('customer'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, User $customer)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,' . $customer->id,
'phone' => 'required|string|max:15',
'address' => 'required|string',
]);
$data = [
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'address' => $request->address,
];
// Jika password baru diisi
if ($request->filled('password')) {
$request->validate([
'password' => 'required|string|min:8',
]);
$data['password'] = Hash::make($request->password);
}
$customer->update($data);
return redirect()->route('admin.customers.index')
->with('success', 'Data pelanggan berhasil diperbarui');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(User $customer)
{
$customer->delete();
return redirect()->route('admin.customers.index')
->with('success', 'Pelanggan berhasil dihapus');
}
}