Files
canteenhub/app/Controllers/CustomerController.php
T

47 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Models\Customer;
class CustomerController extends Controller
{
public function index(Request $request, Response $response): string
{
$customers = Customer::all();
return $this->render('customers/index', [
'title' => 'Customer Directory',
'customers' => $customers,
]);
}
public function store(Request $request, Response $response): Response
{
$name = trim((string)$request->post('name'));
$email = trim((string)$request->post('email'));
$phone = trim((string)$request->post('phone', ''));
$address = trim((string)$request->post('address', ''));
if (empty($name) || empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
return $this->redirect('/customers', null, 'Please provide a valid name and email address.');
}
try {
Customer::create([
'name' => $name,
'email' => $email,
'phone' => $phone,
'address' => $address,
]);
return $this->redirect('/customers', 'Customer registered successfully!');
} catch (\Throwable $e) {
return $this->redirect('/customers', null, 'Error adding customer: ' . $e->getMessage());
}
}
}