Dina Ayu Aisyah Project

This commit is contained in:
dinaayua 2025-07-15 10:37:21 +07:00
commit 23f7778127
215 changed files with 26422 additions and 0 deletions

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

66
.env.example Normal file
View File

@ -0,0 +1,66 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:CmQfwu7hjMs8KUGH9it0vhFGfZBZQXD6iH4IZrEb6YA=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dindin-reserv
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
MIDTRANS_MERCHANT_ID=G032950328
MIDTRANS_CLIENT_KEY=SB-Mid-client-ANPXuv-C8lg-ZU0Y
MIDTRANS_SERVER_KEY=SB-Mid-server-nE3AutUMOJoqDUx_jtY0jcif
MIDTRANS_IS_PRODUCTION=false
MIDTRANS_IS_SANITIZED=true
MIDTRANS_IS_3DS=true

11
.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

19
.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode

66
README.md Normal file
View File

@ -0,0 +1,66 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[WebReinvent](https://webreinvent.com/)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Jump24](https://jump24.co.uk)**
- **[Redberry](https://redberry.international/laravel/)**
- **[Active Logic](https://activelogic.com)**
- **[byte5](https://byte5.de)**
- **[OP.GG](https://op.gg)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

BIN
app.7z Normal file

Binary file not shown.

BIN
app.zip Normal file

Binary file not shown.

27
app/Console/Kernel.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,120 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\CarouselImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class CarouselController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$images = CarouselImage::latest()->get();
return view('admin.carousel', compact('images'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
]);
$imagePath = $request->file('image')->store('carousel', 'public');
CarouselImage::create([
'image' => $imagePath,
'is_active' => true
]);
return redirect()->back()->with('success', 'Gambar carousel berhasil ditambahkan');
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, CarouselImage $carousel)
{
$request->validate([
'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
'is_active' => 'nullable|boolean'
]);
$data = [];
if ($request->hasFile('image')) {
// Delete old image
if ($carousel->image) {
Storage::disk('public')->delete($carousel->image);
}
$data['image'] = $request->file('image')->store('carousel', 'public');
}
if ($request->has('is_active')) {
$data['is_active'] = $request->is_active;
}
$carousel->update($data);
return redirect()->back()->with('success', 'Gambar carousel berhasil diperbarui');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(CarouselImage $carousel)
{
if ($carousel->image) {
Storage::disk('public')->delete($carousel->image);
}
$carousel->delete();
return redirect()->back()->with('success', 'Gambar carousel berhasil dihapus');
}
public function reorder(Request $request)
{
$request->validate([
'orders' => 'required|array',
'orders.*' => 'required|integer|exists:carousel_images,id'
]);
foreach ($request->orders as $index => $id) {
CarouselImage::where('id', $id)->update(['order' => $index]);
}
return response()->json(['success' => true]);
}
}

View File

@ -0,0 +1,224 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\GalleryCategory;
use App\Models\GalleryImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class GalleryController extends Controller
{
public function index()
{
$categories = GalleryCategory::with('images')->get();
return view('admin.gallery.index', compact('categories'));
}
public function storeCategory(Request $request)
{
try {
$request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string',
'thumbnail' => 'required|image|mimes:jpeg,png,jpg|max:2048'
]);
$thumbnailPath = $request->file('thumbnail')->store('gallery/thumbnails', 'public');
$category = GalleryCategory::create([
'name' => $request->name,
'description' => $request->description,
'thumbnail' => $thumbnailPath
]);
return response()->json([
'success' => true,
'message' => 'Kategori galeri berhasil ditambahkan',
'data' => $category
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal menambahkan kategori: ' . $e->getMessage()
], 500);
}
}
public function updateCategory(Request $request, GalleryCategory $category)
{
try {
$request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string',
'thumbnail' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
]);
$data = [
'name' => $request->name,
'description' => $request->description
];
if ($request->hasFile('thumbnail')) {
if ($category->thumbnail) {
Storage::disk('public')->delete($category->thumbnail);
}
$data['thumbnail'] = $request->file('thumbnail')->store('gallery/thumbnails', 'public');
}
$category->update($data);
return response()->json([
'success' => true,
'message' => 'Kategori galeri berhasil diperbarui',
'data' => $category
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal memperbarui kategori: ' . $e->getMessage()
], 500);
}
}
public function destroyCategory(GalleryCategory $category)
{
try {
// Delete thumbnail
if ($category->thumbnail) {
Storage::disk('public')->delete($category->thumbnail);
}
// Delete all related images
foreach ($category->images as $image) {
Storage::disk('public')->delete($image->image);
}
$category->delete();
return response()->json([
'success' => true,
'message' => 'Kategori galeri berhasil dihapus'
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal menghapus kategori: ' . $e->getMessage()
], 500);
}
}
public function storeImage(Request $request, GalleryCategory $category)
{
try {
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
'caption' => 'nullable|string|max:255'
]);
$imagePath = $request->file('image')->store('gallery/images', 'public');
$image = $category->images()->create([
'image' => $imagePath,
'caption' => $request->caption
]);
return response()->json([
'success' => true,
'message' => 'Gambar berhasil ditambahkan ke galeri',
'data' => $image
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal menambahkan gambar: ' . $e->getMessage()
], 500);
}
}
public function updateImage(Request $request, GalleryImage $image)
{
try {
$request->validate([
'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
'caption' => 'nullable|string|max:255'
]);
$data = [];
if ($request->hasFile('image')) {
Storage::disk('public')->delete($image->image);
$data['image'] = $request->file('image')->store('gallery/images', 'public');
}
if ($request->has('caption')) {
$data['caption'] = $request->caption;
}
$image->update($data);
return response()->json([
'success' => true,
'message' => 'Gambar berhasil diperbarui',
'data' => $image
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal memperbarui gambar: ' . $e->getMessage()
], 500);
}
}
public function destroyImage(GalleryImage $image)
{
try {
if ($image->image) {
Storage::disk('public')->delete($image->image);
}
$image->delete();
return response()->json([
'success' => true,
'message' => 'Gambar berhasil dihapus dari galeri'
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal menghapus gambar: ' . $e->getMessage()
], 500);
}
}
public function getCategory(GalleryCategory $category)
{
try {
return response()->json([
'success' => true,
'data' => $category
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Failed to fetch category data: ' . $e->getMessage()
], 500);
}
}
public function getImage(GalleryImage $image)
{
try {
return response()->json([
'success' => true,
'data' => $image
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Failed to fetch image data: ' . $e->getMessage()
], 500);
}
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\KritikSaran;
use Illuminate\Http\Request;
class KritikSaranController extends Controller
{
public function index()
{
$feedbacks = KritikSaran::orderBy('created_at', 'desc')->get();
return view('admin.kritiksaran.index', compact('feedbacks'));
}
public function destroy($id)
{
$feedback = KritikSaran::findOrFail($id);
$feedback->delete();
return redirect()->route('admin.kritiksaran.index')
->with('success', 'Feedback berhasil dihapus');
}
}

View File

@ -0,0 +1,86 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\MenuItem;
use App\Models\MenuCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class MenuController extends Controller
{
public function index()
{
$categories = MenuCategory::all();
$menuItems = MenuItem::with('category')->get();
return view('admin.menu', compact('categories', 'menuItems'));
}
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'price' => 'required|numeric|min:0',
'category_id' => 'required|exists:menu_categories,id',
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
]);
$imagePath = $request->file('image')->store('menu-items', 'public');
MenuItem::create([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
'category_id' => $request->category_id,
'image' => $imagePath,
'is_available' => $request->has('is_available')
]);
return redirect()->back()->with('success', 'Menu berhasil ditambahkan');
}
public function update(Request $request, MenuItem $menuItem)
{
$request->validate([
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'price' => 'required|numeric|min:0',
'category_id' => 'required|exists:menu_categories,id',
'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
]);
$data = [
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
'category_id' => $request->category_id,
'is_available' => $request->has('is_available')
];
if ($request->hasFile('image')) {
// Hapus gambar lama
if ($menuItem->image) {
Storage::disk('public')->delete($menuItem->image);
}
// Upload gambar baru
$data['image'] = $request->file('image')->store('menu-items', 'public');
}
$menuItem->update($data);
return redirect()->back()->with('success', 'Menu berhasil diperbarui');
}
public function destroy(MenuItem $menuItem)
{
if ($menuItem->image) {
Storage::disk('public')->delete($menuItem->image);
}
$menuItem->delete();
return redirect()->back()->with('success', 'Menu berhasil dihapus');
}
}

View File

@ -0,0 +1,277 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Reservasi;
use App\Models\Meja;
use App\Models\User;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
class ReservationController extends Controller
{
public function index()
{
$reservations = Reservasi::with(['user', 'meja'])
->orderBy('date', 'desc')
->orderBy('start_time', 'desc')
->get();
$users = User::where('role', 'user')->get();
// Get all tables regardless of status
$tables = Meja::orderBy('nomor_meja')->get();
return view('admin.reservations', compact('reservations', 'users', 'tables'));
}
public function store(Request $request)
{
$request->validate([
'user_id' => 'required|exists:users,id',
'meja_id' => 'required|exists:meja,id',
'name' => 'required|string|max:255',
'phone' => 'required|string|max:20',
'date' => 'required|date|after_or_equal:today',
'start_time' => 'required|date_format:H:i',
'end_time' => 'required|date_format:H:i|after:start_time',
'notes' => 'nullable|string',
'total_harga' => 'required|numeric|min:0'
]);
// Check if the time slot is available
if (!Reservasi::isTimeSlotAvailable(
$request->meja_id,
$request->date,
$request->start_time,
$request->end_time
)) {
return back()->withErrors(['time' => 'Waktu yang dipilih sudah dipesan']);
}
try {
// Create reservation
$reservation = Reservasi::create([
'user_id' => $request->user_id,
'meja_id' => $request->meja_id,
'name' => $request->name,
'phone' => $request->phone,
'date' => $request->date,
'start_time' => $request->start_time,
'end_time' => $request->end_time,
'notes' => $request->notes,
'status' => 'pending',
'total_harga' => $request->total_harga
]);
// Update table status if reservation is for today
if ($request->date == now()->format('Y-m-d')) {
Meja::where('id', $request->meja_id)
->update(['status' => 'dipesan']);
}
return redirect()->back()->with('success', 'Reservasi berhasil ditambahkan');
} catch (\Exception $e) {
Log::error('Error creating reservation:', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return back()->withErrors(['error' => 'Terjadi kesalahan saat membuat reservasi. Silakan coba lagi.'])->withInput();
}
}
public function update(Request $request, Reservasi $reservation)
{
$request->validate([
'status' => 'required|in:pending,confirmed,completed,cancelled',
'meja_id' => 'required|exists:meja,id'
]);
// Update both status and table
$reservation->update([
'status' => $request->status,
'meja_id' => $request->meja_id
]);
// Update table status based on reservation status
if ($reservation->date == now()->format('Y-m-d')) {
if ($request->status === 'confirmed') {
$reservation->meja()->update(['status' => 'dipesan']);
} elseif (in_array($request->status, ['completed', 'cancelled'])) {
$reservation->meja()->update(['status' => 'tersedia']);
}
}
if ($request->ajax()) {
return response()->json([
'success' => true,
'message' => 'Reservasi berhasil diperbarui'
]);
}
return redirect()->back()->with('success', 'Reservasi berhasil diperbarui');
}
public function destroy(Reservasi $reservation)
{
try {
// Set table status back to available if reservation was for today
if ($reservation->date == now()->format('Y-m-d') && $reservation->meja) {
$reservation->meja()->update(['status' => 'tersedia']);
}
$reservation->delete();
return redirect()->back()->with('success', 'Reservasi berhasil dihapus');
} catch (\Exception $e) {
Log::error('Error deleting reservation:', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return back()->withErrors(['error' => 'Terjadi kesalahan saat menghapus reservasi.']);
}
}
public function getAvailableTimeSlots(Request $request)
{
try {
Log::info('Admin getAvailableTimeSlots called with request:', [
'all_params' => $request->all(),
'date' => $request->date,
'meja_id' => $request->meja_id
]);
$request->validate([
'meja_id' => 'required|exists:meja,id',
'date' => 'required|date|after_or_equal:today',
]);
Log::info('Validation passed, getting reservations');
// Get existing reservations for this table and date
$reservations = Reservasi::where('meja_id', $request->meja_id)
->whereDate('date', $request->date)
->whereNotIn('status', ['cancelled'])
->get();
Log::info('Found existing reservations', [
'count' => $reservations->count(),
'reservations' => $reservations->toArray()
]);
$timeSlots = [];
$startHour = 10; // 10:00
$endHour = 22; // 22:00
$interval = 30; // 30 minutes interval
Log::info('Starting to generate time slots');
// Create a helper function to check if a time slot is reserved
$isTimeSlotReserved = function($checkTime) use ($reservations) {
$checkDateTime = Carbon::parse($checkTime);
foreach ($reservations as $reservation) {
$reservationStart = Carbon::parse($reservation->start_time);
$reservationEnd = Carbon::parse($reservation->end_time);
if ($checkDateTime->between($reservationStart, $reservationEnd, true)) {
return true;
}
}
return false;
};
// Generate all possible time slots
for ($hour = $startHour; $hour < $endHour; $hour++) {
for ($minute = 0; $minute < 60; $minute += $interval) {
$currentTime = sprintf('%02d:%02d', $hour, $minute);
// Check if this time slot is already reserved
$isReserved = $isTimeSlotReserved($currentTime);
if (!$isReserved) {
$endTimeOptions = [];
// Generate possible end times (30 minutes to 4 hours after start time)
for ($duration = 30; $duration <= 240; $duration += 30) {
$potentialEndTime = Carbon::parse($currentTime)->addMinutes($duration);
// Don't add end times past closing time
if ($potentialEndTime->format('H:i') > '22:00') {
continue;
}
// Check if any time between start and potential end time is reserved
$hasConflict = false;
$checkTime = Carbon::parse($currentTime);
while ($checkTime < $potentialEndTime) {
if ($isTimeSlotReserved($checkTime->format('H:i'))) {
$hasConflict = true;
break;
}
$checkTime->addMinutes(30);
}
if (!$hasConflict) {
$endTimeOptions[] = $potentialEndTime->format('H:i');
}
}
// Only add start time if it has at least one valid end time option
if (count($endTimeOptions) > 0) {
$timeSlots[] = [
'start_time' => $currentTime,
'end_time_options' => $endTimeOptions,
'is_available' => true
];
}
} else {
// Add reserved time slot
$timeSlots[] = [
'start_time' => $currentTime,
'end_time_options' => [],
'is_available' => false
];
}
}
}
// If date is today, remove past time slots
if ($request->date == Carbon::today()->format('Y-m-d')) {
$currentTime = Carbon::now();
Log::info('Filtering past time slots for today', [
'current_time' => $currentTime->format('H:i'),
'before_count' => count($timeSlots)
]);
$timeSlots = array_filter($timeSlots, function($slot) use ($currentTime) {
return Carbon::parse($slot['start_time'])->gt($currentTime);
});
Log::info('After filtering past slots', [
'after_count' => count($timeSlots)
]);
}
$timeSlots = array_values($timeSlots);
Log::info('Generated available time slots', [
'count' => count($timeSlots),
'first_few_slots' => array_slice($timeSlots, 0, 3)
]);
return response()->json([
'success' => true,
'data' => $timeSlots
]);
} catch (\Exception $e) {
Log::error('Error in admin getAvailableTimeSlots', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'success' => false,
'message' => 'Terjadi kesalahan saat memuat jadwal: ' . $e->getMessage()
], 500);
}
}
}

View File

@ -0,0 +1,168 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Meja;
use App\Models\Reservasi;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
class TableController extends Controller
{
public function index()
{
$tables = Meja::orderBy('nomor_meja')->get();
return view('admin.tables', compact('tables'));
}
public function store(Request $request)
{
try {
$request->validate([
'nomor_meja' => 'required|string|unique:meja,nomor_meja',
'kapasitas' => 'required|integer|min:1',
'kategori' => 'required|in:outdoor,vip-outdoor,vip-indoor',
'status' => 'required|in:tersedia,tidak_tersedia',
'deskripsi' => 'nullable|string',
'gambar' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
$data = $request->except('gambar');
if ($request->hasFile('gambar')) {
$gambar = $request->file('gambar');
$filename = 'meja_' . time() . '_' . Str::random(10) . '.' . $gambar->getClientOriginalExtension();
// Store file in public disk
$path = $gambar->storeAs('meja', $filename, 'public');
if (!$path) {
throw new \Exception('Gagal mengupload gambar');
}
$data['gambar'] = $path;
}
$table = Meja::create($data);
if ($request->ajax()) {
return response()->json([
'status' => 'success',
'message' => 'Meja berhasil ditambahkan',
'data' => $table
]);
}
return redirect()->back()->with('success', 'Meja berhasil ditambahkan');
} catch (\Exception $e) {
Log::error('Error in TableController@store: ' . $e->getMessage());
if ($request->ajax()) {
return response()->json([
'status' => 'error',
'message' => 'Terjadi kesalahan saat menambahkan meja: ' . $e->getMessage()
], 500);
}
return redirect()->back()
->with('error', 'Terjadi kesalahan saat menambahkan meja: ' . $e->getMessage())
->withInput();
}
}
public function update(Request $request, Meja $table)
{
try {
$request->validate([
'nomor_meja' => 'required|string|unique:meja,nomor_meja,' . $table->id,
'kapasitas' => 'required|integer|min:1',
'kategori' => 'required|in:outdoor,vip-outdoor,vip-indoor',
'status' => 'required|in:tersedia,tidak_tersedia',
'deskripsi' => 'nullable|string',
'gambar' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
$data = $request->except('gambar');
if ($request->hasFile('gambar')) {
// Hapus gambar lama jika ada
if ($table->gambar) {
Storage::disk('public')->delete($table->gambar);
}
$gambar = $request->file('gambar');
$filename = 'meja_' . time() . '_' . Str::random(10) . '.' . $gambar->getClientOriginalExtension();
// Store file in public disk
$path = $gambar->storeAs('meja', $filename, 'public');
if (!$path) {
throw new \Exception('Gagal mengupload gambar');
}
$data['gambar'] = $path;
}
$table->update($data);
if ($request->ajax()) {
return response()->json([
'status' => 'success',
'message' => 'Meja berhasil diperbarui',
'data' => $table
]);
}
return redirect()->back()->with('success', 'Meja berhasil diperbarui');
} catch (\Exception $e) {
Log::error('Error in TableController@update: ' . $e->getMessage());
if ($request->ajax()) {
return response()->json([
'status' => 'error',
'message' => 'Terjadi kesalahan saat memperbarui meja: ' . $e->getMessage()
], 500);
}
return redirect()->back()
->with('error', 'Terjadi kesalahan saat memperbarui meja: ' . $e->getMessage())
->withInput();
}
}
public function destroy(Meja $table)
{
try {
// Hapus gambar jika ada
if ($table->gambar) {
Storage::disk('public')->delete($table->gambar);
}
$table->delete();
return redirect()->back()->with('success', 'Meja berhasil dihapus');
} catch (\Exception $e) {
Log::error('Error in TableController@destroy: ' . $e->getMessage());
return redirect()->back()->with('error', 'Terjadi kesalahan saat menghapus meja: ' . $e->getMessage());
}
}
public function getSchedule(Request $request, $id)
{
$request->validate([
'date' => 'required|date'
]);
$reservations = Reservasi::where('meja_id', $id)
->whereDate('date', $request->date)
->where('status', '!=', 'cancelled')
->select('name', 'people', 'start_time', 'end_time', 'status')
->orderBy('start_time')
->get();
return response()->json([
'success' => true,
'reservations' => $reservations
]);
}
}

View File

@ -0,0 +1,196 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Reservasi;
use App\Models\Meja;
use Illuminate\Support\Facades\Auth;
use App\Models\Transaksi;
class AdminController extends Controller
{
public function dashboard(Request $request)
{
$period = $request->get('period', 'daily'); // daily, weekly, monthly, yearly
// Get date ranges based on period
$dateRange = $this->getDateRange($period);
$startDate = $dateRange['start'];
$endDate = $dateRange['end'];
// Mengambil data untuk dashboard dengan filter periode
$totalReservasi = Reservasi::whereBetween('created_at', [$startDate, $endDate])->count();
// Menghitung total pendapatan dari transaksi yang sudah dibayar (paid) atau selesai (completed)
$totalPendapatan = Transaksi::whereIn('status', ['paid', 'completed'])
->whereBetween('created_at', [$startDate, $endDate])
->sum('total_amount');
// Menghitung jumlah meja yang tersedia
$mejaKosong = Meja::where('status', 'tersedia')->count();
// Menghitung jumlah reservasi berdasarkan status dengan filter periode
$reservasiSuccess = Reservasi::whereIn('status', ['confirmed', 'completed'])
->whereBetween('created_at', [$startDate, $endDate])
->count();
$reservasiPending = Reservasi::where('status', 'pending')
->whereBetween('created_at', [$startDate, $endDate])
->count();
$reservasiCancelled = Reservasi::where('status', 'cancelled')
->whereBetween('created_at', [$startDate, $endDate])
->count();
// Data untuk chart default (tampilan hari ini per jam)
$chartData = $this->getChartData($period);
return view('admin.dashboard', compact(
'totalReservasi',
'totalPendapatan',
'mejaKosong',
'reservasiSuccess',
'reservasiPending',
'reservasiCancelled',
'chartData',
'period'
));
}
private function getDateRange($period)
{
$now = now();
switch ($period) {
case 'daily':
return [
'start' => $now->startOfDay(),
'end' => $now->copy()->endOfDay(),
];
case 'weekly':
return [
'start' => $now->startOfWeek(),
'end' => $now->copy()->endOfWeek(),
];
case 'monthly':
return [
'start' => $now->startOfMonth(),
'end' => $now->copy()->endOfMonth(),
];
case 'yearly':
return [
'start' => $now->startOfYear(),
'end' => $now->copy()->endOfYear(),
];
default:
return [
'start' => $now->startOfDay(),
'end' => $now->copy()->endOfDay(),
];
}
}
public function getChartData($period = 'daily')
{
$query = Transaksi::whereIn('status', ['paid', 'completed']);
$dateRange = $this->getDateRange($period);
switch ($period) {
case 'daily':
// Data per jam untuk hari ini
$data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
->selectRaw('HOUR(created_at) as label, SUM(total_amount) as value')
->groupBy('label')
->orderBy('label')
->get()
->map(function ($item) {
return [
'label' => sprintf('%02d:00', $item->label),
'value' => $item->value
];
});
break;
case 'weekly':
// Data per hari dalam minggu ini
$data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
->selectRaw('DATE(created_at) as label, SUM(total_amount) as value')
->groupBy('label')
->orderBy('label')
->get()
->map(function ($item) {
return [
'label' => date('D, d M', strtotime($item->label)),
'value' => $item->value
];
});
break;
case 'monthly':
// Data per minggu dalam bulan ini
$data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
->selectRaw('WEEK(created_at) as week, SUM(total_amount) as value')
->groupBy('week')
->orderBy('week')
->get()
->map(function ($item) {
$weekStart = now()->setISODate(now()->year, $item->week);
return [
'label' => 'Minggu ' . $weekStart->format('W'),
'value' => $item->value
];
});
break;
case 'yearly':
// Data per bulan dalam tahun ini
$data = $query->whereBetween('created_at', [$dateRange['start'], $dateRange['end']])
->selectRaw('MONTH(created_at) as month, SUM(total_amount) as value')
->groupBy('month')
->orderBy('month')
->get()
->map(function ($item) {
return [
'label' => date('F', mktime(0, 0, 0, $item->month, 1)),
'value' => $item->value
];
});
break;
default:
$data = collect([]);
}
// Format response
return [
'labels' => $data->pluck('label'),
'values' => $data->pluck('value'),
];
}
public function ajaxChartData(Request $request)
{
$period = $request->get('period', 'daily');
return response()->json($this->getChartData($period));
}
public function reservations()
{
// Menampilkan daftar reservasi
$reservations = Reservasi::latest()->paginate(10);
return view('admin.reservations', compact('reservations'));
}
public function tables()
{
// Menampilkan daftar meja
$tables = Meja::all();
return view('admin.tables', compact('tables'));
}
public function logout(Request $request)
{
Auth::logout();
return redirect('/login')->with('success', 'Berhasil logout');
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::attempt($credentials, $request->boolean('remember'))) {
$request->session()->regenerate();
return redirect()->intended('/dashboard');
}
return back()->withErrors([
'email' => 'Email atau password salah.',
]);
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/login');
}
public function authenticated(Request $request, $user)
{
if ($user->role === 'admin') {
return redirect()->route('admin.dashboard');
}
return redirect()->route('home');
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class RegisterController extends Controller
{
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
auth()->login($user);
return redirect('/');
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Auth\Events\PasswordReset;
class AuthController extends Controller
{
public function showLogin()
{
return view('auth.login');
}
public function showRegister()
{
return view('auth.register');
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
// Redirect berdasarkan role
if (Auth::user()->role === 'admin') {
return redirect()->route('admin.dashboard');
}
return redirect()->route('menu.index');
}
return back()->with('error', 'Email atau password salah!');
}
public function register(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:5|confirmed',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => 'user'
]);
Auth::login($user);
// Redirect user baru ke halaman menu
return redirect()->route('menu.index')->with('success', 'Registrasi berhasil!');
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
public function showForgotPassword()
{
return view('auth.forgot-password');
}
public function sendResetLink(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users,email'
]);
$status = Password::sendResetLink(
$request->only('email')
);
return $status === Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withErrors(['email' => __($status)]);
}
public function showResetPassword(string $token, Request $request)
{
return view('auth.reset-password', [
'token' => $token,
'email' => $request->email
]);
}
public function resetPassword(Request $request)
{
$request->validate([
'token' => 'required',
'email' => 'required|email|exists:users,email',
'password' => 'required|min:8|confirmed',
]);
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user, $password) {
$user->forceFill([
'password' => Hash::make($password)
])->setRememberToken(Str::random(60));
$user->save();
event(new PasswordReset($user));
}
);
return $status === Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withErrors(['email' => [__($status)]]);
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace App\Http\Controllers;
use App\Models\Bestseller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class BestsellerController extends Controller
{
public function index()
{
$bestsellers = Bestseller::all();
return view('admin.bestseller.index', compact('bestsellers'));
}
public function getBestsellers()
{
$bestsellers = Bestseller::all();
return $bestsellers;
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
$image = $request->file('image');
$imageName = time() . '.' . $image->extension();
$image->storeAs('public/bestsellers', $imageName);
Bestseller::create([
'name' => $request->name,
'description' => $request->description,
'image' => $imageName
]);
return redirect()->back()->with('success', 'Bestseller added successfully');
}
public function update(Request $request, Bestseller $bestseller)
{
$request->validate([
'name' => 'required',
'description' => 'required',
'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
$data = [
'name' => $request->name,
'description' => $request->description
];
if ($request->hasFile('image')) {
// Delete old image
if ($bestseller->image) {
Storage::delete('public/bestsellers/' . $bestseller->image);
}
// Store new image
$image = $request->file('image');
$imageName = time() . '.' . $image->extension();
$image->storeAs('public/bestsellers', $imageName);
$data['image'] = $imageName;
}
$bestseller->update($data);
return redirect()->back()->with('success', 'Bestseller updated successfully');
}
public function destroy(Bestseller $bestseller)
{
if ($bestseller->image) {
Storage::delete('public/bestsellers/' . $bestseller->image);
}
$bestseller->delete();
return redirect()->back()->with('success', 'Bestseller deleted successfully');
}
}

View File

@ -0,0 +1,264 @@
<?php
namespace App\Http\Controllers;
use App\Models\Cart;
use App\Models\MenuItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
class CartController extends Controller
{
public function index()
{
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get();
$totals = Cart::calculateTotals($cartItems);
return view('cart.index', compact('cartItems', 'totals'));
}
public function add(Request $request)
{
try {
Log::info('Add to Cart Request:', [
'request_data' => $request->all(),
'user_id' => Auth::id(),
'is_authenticated' => Auth::check()
]);
if (!Auth::check()) {
Log::warning('Unauthorized attempt to add to cart');
return response()->json([
'status' => 'error',
'message' => 'Silakan login terlebih dahulu'
], 401);
}
$menu = MenuItem::findOrFail($request->menu_id);
Log::info('Found menu item:', [
'menu_id' => $menu->id,
'menu_name' => $menu->name,
'menu_price' => $menu->price
]);
DB::beginTransaction();
try {
$cart = Cart::where('user_id', Auth::id())
->where('menu_id', $menu->id)
->first();
Log::info('Existing cart item:', [
'exists' => (bool)$cart,
'cart_data' => $cart ? $cart->toArray() : null
]);
if ($cart) {
// Update existing cart item
$cart->quantity += 1;
$cart->subtotal = $cart->quantity * $menu->price;
$cart->save();
Log::info('Updated existing cart item:', $cart->toArray());
} else {
// Create new cart item
$cart = Cart::create([
'user_id' => Auth::id(),
'menu_id' => $menu->id,
'quantity' => 1,
'price' => $menu->price,
'subtotal' => $menu->price,
]);
Log::info('Created new cart item:', $cart->toArray());
}
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get();
Log::info('All cart items after update:', [
'items_count' => $cartItems->count(),
'items' => $cartItems->toArray()
]);
$mappedItems = $cartItems->map(function ($item) {
return [
'id' => $item->id,
'name' => $item->menu->name,
'price' => $item->price,
'quantity' => $item->quantity,
'subtotal' => $item->price * $item->quantity,
'image' => $item->menu->image
];
})->values();
$totalItems = $cartItems->sum('quantity');
$totalHarga = $cartItems->sum('subtotal');
DB::commit();
Log::info('Cart operation successful', [
'total_items' => $totalItems,
'total_harga' => $totalHarga
]);
return response()->json([
'status' => 'success',
'message' => 'Item berhasil ditambahkan ke keranjang',
'cartCount' => $totalItems,
'cartItems' => $mappedItems,
'totalHarga' => $totalHarga
]);
} catch (\Exception $e) {
DB::rollback();
Log::error('Database Error in add to cart:', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
throw $e;
}
} catch (\Exception $e) {
Log::error('Error in add to cart:', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'request_data' => $request->all()
]);
return response()->json([
'status' => 'error',
'message' => 'Gagal menambahkan item ke keranjang: ' . $e->getMessage()
], 500);
}
}
public function update(Request $request)
{
$request->validate([
'cart_id' => 'required|exists:carts,id',
'quantity' => 'required|integer|min:1'
]);
$cart = Cart::where('user_id', Auth::id())
->where('id', $request->cart_id)
->firstOrFail();
$cart->quantity = $request->quantity;
$cart->subtotal = $cart->price * $cart->quantity;
$cart->save();
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get()
->map(function ($item) {
return [
'id' => $item->id,
'menu_id' => $item->menu_id,
'name' => $item->menu->name,
'price' => $item->price,
'quantity' => $item->quantity,
'subtotal' => $item->price * $item->quantity,
'image' => $item->menu->image
];
});
$totals = Cart::calculateTotals($cartItems);
return response()->json([
'status' => 'success',
'message' => 'Keranjang berhasil diupdate',
'cartItems' => $cartItems,
'cartCount' => $cartItems->sum('quantity'),
'totalHarga' => $totals['total']
]);
}
public function remove(Request $request)
{
$cart = Cart::where('user_id', Auth::id())
->where('id', $request->cart_id)
->firstOrFail();
$cart->delete();
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get()
->map(function ($item) {
return [
'id' => $item->id,
'menu_id' => $item->menu_id,
'name' => $item->menu->name,
'price' => $item->price,
'quantity' => $item->quantity,
'subtotal' => $item->subtotal,
'image' => $item->menu->image
];
});
$totals = Cart::calculateTotals($cartItems);
return response()->json([
'status' => 'success',
'message' => 'Item berhasil dihapus dari keranjang',
'cartCount' => $cartItems->sum('quantity'),
'cartItems' => $cartItems,
'totals' => $totals
]);
}
public function clear()
{
Cart::where('user_id', Auth::id())->delete();
return response()->json([
'status' => 'success',
'message' => 'Keranjang berhasil dikosongkan'
]);
}
public function getCart()
{
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get();
// Debug log
Log::info('Cart Items:', [
'raw' => $cartItems->toArray(),
]);
$mappedItems = $cartItems->map(function ($item) {
return [
'id' => $item->id,
'menu_id' => $item->menu_id,
'name' => $item->menu->name,
'price' => $item->price,
'quantity' => $item->quantity,
'subtotal' => $item->subtotal,
'image' => $item->menu->image
];
});
// Debug log
Log::info('Mapped Items:', [
'mapped' => $mappedItems->toArray(),
]);
$totals = Cart::calculateTotals($cartItems);
return response()->json([
'status' => 'success',
'cartItems' => $mappedItems,
'cartCount' => $cartItems->sum('quantity'),
'totalHarga' => $totals['total']
]);
}
}

View File

@ -0,0 +1,87 @@
<?php
namespace App\Http\Controllers;
use App\Models\Cart;
use App\Models\Transaksi;
use App\Models\TransaksiItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class CheckoutController extends Controller
{
public function index()
{
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get();
if($cartItems->isEmpty()) {
return redirect()->route('menu.index')->with('error', 'Keranjang belanja kosong!');
}
$totals = Cart::calculateTotals($cartItems);
return view('checkout', compact('cartItems', 'totals'));
}
public function process(Request $request)
{
$request->validate([
'payment_method' => 'required|in:cash,transfer,qris',
'notes' => 'nullable|string|max:500'
]);
try {
DB::beginTransaction();
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get();
if($cartItems->isEmpty()) {
return redirect()->route('menu.index')->with('error', 'Keranjang belanja kosong!');
}
$totals = Cart::calculateTotals($cartItems);
// Buat transaksi baru
$transaksi = Transaksi::create([
'user_id' => Auth::id(),
'transaction_code' => 'TRX-' . time(),
'tax_amount' => $totals['tax'],
'service_charge' => $totals['service'],
'final_amount' => $totals['final'],
'payment_method' => $request->payment_method,
'notes' => $request->notes
]);
// Simpan item transaksi
foreach($cartItems as $item) {
TransaksiItem::create([
'transaksi_id' => $transaksi->id,
'menu_id' => $item->menu_id,
'menu_name' => $item->menu->name,
'quantity' => $item->quantity,
'price' => $item->price,
'subtotal' => $item->subtotal,
'notes' => $item->notes
]);
}
// Kosongkan cart
Cart::where('user_id', Auth::id())->delete();
DB::commit();
return redirect()->route('transaksi.show', $transaksi->id)
->with('success', 'Pesanan berhasil diproses!');
} catch(\Exception $e) {
DB::rollback();
return redirect()->back()
->with('error', 'Terjadi kesalahan saat memproses pesanan. Silakan coba lagi.');
}
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\CarouselImage;
use App\Models\GalleryCategory;
use App\Models\Bestseller;
class DashboardController extends Controller
{
public function index()
{
$carouselImages = CarouselImage::where('is_active', true)
->latest()
->get();
$galleryCategories = GalleryCategory::with('images')->get();
$bestsellers = Bestseller::all();
return view('dashboard', compact('carouselImages', 'galleryCategories', 'bestsellers'));
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
return view('home');
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\KritikSaran;
class KritikSaranController extends Controller
{
public function index()
{
return view('kritiksaran');
}
public function store(Request $request)
{
// Validasi input
$request->validate([
'nama' => 'required',
'email' => 'required|email',
'jenis' => 'required|in:kritik,saran',
'pesan' => 'required|min:10'
]);
// Simpan kritik & saran
KritikSaran::create([
'user_id' => auth()->id(),
'nama' => $request->nama,
'email' => $request->email,
'jenis' => $request->jenis,
'pesan' => $request->pesan
]);
return redirect()->back()->with('success', 'Terima kasih atas feedback Anda!');
}
public function show($id)
{
// Menampilkan detail feedback
$feedback = KritikSaran::findOrFail($id);
return view('kritik-saran.show', compact('feedback'));
}
public function destroy($id)
{
// Hapus feedback
$feedback = KritikSaran::findOrFail($id);
$feedback->delete();
return redirect()->route('kritik-saran.index')
->with('success', 'Feedback berhasil dihapus');
}
}

View File

@ -0,0 +1,77 @@
<?php
namespace App\Http\Controllers;
use App\Models\Bestseller;
use App\Models\CarouselImage;
use App\Models\GalleryCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class LandingPageController extends Controller
{
public function index()
{
$bestsellers = Bestseller::all();
$carouselImages = CarouselImage::where('is_active', true)
->latest()
->get();
$galleryCategories = GalleryCategory::with('images')->get();
return view('landingpage', compact('bestsellers', 'carouselImages', 'galleryCategories'));
}
public function store(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
]);
$imagePath = $request->file('image')->store('carousel', 'public');
CarouselImage::create([
'image' => $imagePath,
'is_active' => true
]);
return redirect()->back()->with('success', 'Gambar carousel berhasil ditambahkan');
}
public function update(Request $request, CarouselImage $carousel)
{
$request->validate([
'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
'is_active' => 'nullable|boolean'
]);
$data = [];
if ($request->hasFile('image')) {
// Delete old image
if ($carousel->image) {
Storage::disk('public')->delete($carousel->image);
}
$data['image'] = $request->file('image')->store('carousel', 'public');
}
if ($request->has('is_active')) {
$data['is_active'] = $request->is_active;
}
$carousel->update($data);
return redirect()->back()->with('success', 'Gambar carousel berhasil diperbarui');
}
public function destroy(CarouselImage $carousel)
{
if ($carousel->image) {
Storage::disk('public')->delete($carousel->image);
}
$carousel->delete();
return redirect()->back()->with('success', 'Gambar carousel berhasil dihapus');
}
}

View File

@ -0,0 +1,150 @@
<?php
namespace App\Http\Controllers;
use App\Models\Meja;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;
class MejaController extends Controller
{
public function index()
{
$mejas = Meja::where('status', 'tersedia')->get();
return view('meja', compact('mejas'));
}
public function selectMeja(Request $request)
{
try {
$request->validate([
'meja_id' => 'required|exists:meja,id'
], [
'meja_id.required' => 'Silakan pilih meja terlebih dahulu',
'meja_id.exists' => 'Meja yang dipilih tidak valid'
]);
$meja = Meja::findOrFail($request->meja_id);
// Check if table is available
if ($meja->status !== 'tersedia') {
return back()->with('error', 'Meja tidak tersedia.');
}
// Store selected meja in session
session(['selected_meja' => $meja->id]);
return redirect()->route('reservasi.index');
} catch (\Exception $e) {
Log::error('Error in MejaController@selectMeja: ' . $e->getMessage());
return back()->with('error', 'Terjadi kesalahan. Silakan coba lagi.');
}
}
public function checkAvailability(Request $request, $id)
{
try {
$request->validate([
'date' => 'required|date|after_or_equal:today'
]);
$meja = Meja::findOrFail($id);
$date = $request->date;
// Get available time slots for the date
$slots = $meja->getAvailableTimeSlots($date);
// Filter out past slots if date is today
if ($date === date('Y-m-d')) {
$currentTime = Carbon::now();
$slots = array_filter($slots, function($slot) use ($currentTime) {
return Carbon::parse($slot)->gt($currentTime);
});
}
if (empty($slots)) {
return response()->json([
'available' => false,
'slots' => [],
'message' => 'Tidak ada slot waktu tersedia untuk tanggal ini'
]);
}
return response()->json([
'available' => true,
'slots' => $slots,
'message' => 'Slot waktu tersedia'
]);
} catch (\Exception $e) {
Log::error('Error checking meja availability: ' . $e->getMessage());
return response()->json([
'error' => 'Terjadi kesalahan saat memeriksa ketersediaan meja.'
], 500);
}
}
public function getNextAvailableDates(Request $request)
{
try {
$request->validate([
'current_date' => 'required|date'
]);
$currentDate = Carbon::parse($request->current_date);
$availableDates = [];
$daysToCheck = 30; // Check next 30 days
// Get all mejas
$mejas = Meja::all();
// Check each day for the next 30 days
for ($i = 1; $i <= $daysToCheck; $i++) {
$checkDate = $currentDate->copy()->addDays($i);
// Check if any meja has available slots on this date
foreach ($mejas as $meja) {
if ($meja->hasAvailableSlotsForDate($checkDate->format('Y-m-d'))) {
$availableDates[] = $checkDate->format('Y-m-d');
break; // Found an available meja for this date, move to next date
}
}
// Limit to first 5 available dates
if (count($availableDates) >= 5) {
break;
}
}
return response()->json([
'dates' => $availableDates
]);
} catch (\Exception $e) {
Log::error('Error getting next available dates: ' . $e->getMessage());
return response()->json([
'error' => 'Terjadi kesalahan saat mencari tanggal tersedia.'
], 500);
}
}
public function updateStatus(Request $request, $id)
{
$request->validate([
'status' => ['required', Rule::in(['tersedia', 'tidak_tersedia'])]
]);
$meja = Meja::findOrFail($id);
$meja->status = $request->status;
$meja->save();
return response()->json([
'message' => 'Status meja berhasil diperbarui'
]);
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers;
use App\Models\MenuItem;
use App\Models\MenuCategory;
use App\Models\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
class MenuController extends Controller
{
public function index()
{
$categories = MenuCategory::all();
$menus = MenuItem::with('category')->where('is_available', true)->get();
// Ambil cart dari database
$cartItems = Cart::where('user_id', Auth::id())
->with('menu')
->get();
$totals = Cart::calculateTotals($cartItems);
// Convert cart items untuk tampilan
$cart = [];
foreach ($cartItems as $item) {
$cart[$item->menu_id] = [
"id" => $item->menu_id,
"name" => $item->menu->name,
"quantity" => $item->quantity,
"price" => $item->price,
"image" => $item->menu->image,
"subtotal" => $item->subtotal
];
}
return view('menu', compact('menus', 'categories', 'cart', 'totals'));
}
}

View File

@ -0,0 +1,82 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
class ProfileController extends Controller
{
public function show()
{
return view('profile.show', [
'user' => Auth::user()
]);
}
public function edit()
{
return view('profile.edit', [
'user' => Auth::user()
]);
}
public function update(Request $request)
{
$user = Auth::user();
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
'phone' => ['nullable', 'string', 'max:20'],
'address' => ['nullable', 'string', 'max:255'],
'birth_date' => ['nullable', 'date'],
'gender' => ['nullable', Rule::in(['male', 'female'])],
'profile_picture' => ['nullable', 'image', 'max:2048'], // Max 2MB
]);
if ($request->hasFile('profile_picture')) {
// Delete old profile picture if exists
if ($user->profile_picture) {
Storage::disk('public')->delete($user->profile_picture);
}
// Store new profile picture
$path = $request->file('profile_picture')->store('profile-pictures', 'public');
$validated['profile_picture'] = $path;
}
$user->update($validated);
return redirect()->route('profile.show')->with('success', 'Profil berhasil diperbarui!');
}
public function updatePassword(Request $request)
{
$validated = $request->validate([
'current_password' => ['required', 'current_password'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
Auth::user()->update([
'password' => Hash::make($validated['password'])
]);
return back()->with('success', 'Password berhasil diperbarui!');
}
public function deleteProfilePicture()
{
$user = Auth::user();
if ($user->profile_picture) {
Storage::disk('public')->delete($user->profile_picture);
$user->update(['profile_picture' => null]);
}
return back()->with('success', 'Foto profil berhasil dihapus!');
}
}

View File

@ -0,0 +1,305 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
use App\Models\Reservasi;
use App\Models\Meja;
use App\Models\Transaksi;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\Cart;
use App\Models\TransaksiItem;
class ReservasiController extends Controller
{
// Tampilkan formulir reservasi
public function index()
{
try {
$mejaId = session('selected_meja');
$meja = $mejaId ? Meja::findOrFail($mejaId) : null;
$cartItems = auth()->check() ? Cart::where('user_id', auth()->id())->with('menu')->get() : collect();
$totals = [
'subtotal' => 0
];
if ($cartItems->count() > 0) {
$subtotal = $cartItems->sum(function ($item) {
return $item->quantity * $item->menu->price;
});
$totals = [
'subtotal' => $subtotal
];
}
return view('reservasi', compact('meja', 'cartItems', 'totals'));
} catch (\Exception $e) {
Log::error('Error in ReservasiController@index: ' . $e->getMessage());
return redirect()->route('menu.index')->with('error', 'Terjadi kesalahan. Silakan coba lagi.');
}
}
// Simpan data reservasi
public function store(Request $request)
{
DB::beginTransaction();
try {
// Validasi input
$request->validate([
'tanggal' => 'required|date|after_or_equal:today',
'start_time' => 'required'
]);
$mejaId = session('selected_meja');
if (!$mejaId) {
throw new \Exception('Silakan pilih meja terlebih dahulu');
}
// Cek ketersediaan meja
$meja = Meja::findOrFail($mejaId);
if ($meja->status === 'tidak_tersedia') {
throw new \Exception('Meja tidak tersedia');
}
// Ambil items dari cart
$cartItems = Cart::where('user_id', auth()->id())
->with('menu')
->get();
if ($cartItems->isEmpty()) {
throw new \Exception('Keranjang belanja kosong');
}
// Hitung total harga
$totalHarga = $cartItems->sum(function($item) {
return $item->quantity * $item->menu->price;
});
// Final amount sama dengan total harga karena tidak ada tax dan service charge
$finalAmount = $totalHarga;
// Buat reservasi
$reservasi = Reservasi::create([
'meja_id' => $mejaId,
'user_id' => auth()->id(),
'date' => $request->tanggal,
'start_time' => $request->start_time,
'status' => 'pending',
'name' => auth()->user()->name,
'phone' => auth()->user()->phone ?? '',
'total_harga' => $totalHarga
]);
// Generate kode transaksi
$transactionCode = 'TRX-' . date('Ymd') . '-' . strtoupper(uniqid());
// Buat transaksi
$transaksi = Transaksi::create([
'transaction_code' => $transactionCode,
'user_id' => auth()->id(),
'reservasi_id' => $reservasi->id,
'total_amount' => $totalHarga,
'final_amount' => $finalAmount,
'status' => 'pending'
]);
// Simpan item transaksi
foreach ($cartItems as $item) {
TransaksiItem::create([
'transaksi_id' => $transaksi->id,
'menu_id' => $item->menu_id,
'menu_name' => $item->menu->name,
'quantity' => $item->quantity,
'price' => $item->menu->price,
'subtotal' => $item->quantity * $item->menu->price
]);
}
// Update status meja jika reservasi untuk hari ini
if ($request->tanggal === date('Y-m-d')) {
$meja->status = 'dipesan';
$meja->save();
}
// Hapus cart items
Cart::where('user_id', auth()->id())->delete();
// Clear session meja
session()->forget('selected_meja');
DB::commit();
// Redirect ke halaman detail transaksi
return redirect()->route('transaksi.detail', $transaksi->id)
->with('success', 'Reservasi berhasil dibuat, silakan lakukan pembayaran');
} catch (\Exception $e) {
DB::rollback();
Log::error('Error creating reservation and transaction: ' . $e->getMessage());
return back()->with('error', 'Terjadi kesalahan saat membuat reservasi: ' . $e->getMessage());
}
}
public function success($id)
{
$reservasi = Reservasi::with('meja')->findOrFail($id);
return view('reservasi.success', compact('reservasi'));
}
public function checkAvailability(Request $request)
{
$request->validate([
'tanggal' => 'required|date',
'meja_id' => 'required|exists:mejas,id'
]);
$reservasi = Reservasi::where('meja_id', $request->meja_id)
->where('tanggal', $request->tanggal)
->get();
$bookedHours = [];
foreach ($reservasi as $r) {
$startTime = Carbon::parse($r->jam);
for ($i = 0; $i < $r->durasi; $i++) {
$bookedHours[] = $startTime->copy()->addHours($i)->format('H:i');
}
}
$availableHours = [];
$start = Carbon::parse('10:00');
$end = Carbon::parse('22:00');
while ($start <= $end) {
if (!in_array($start->format('H:i'), $bookedHours)) {
$availableHours[] = $start->format('H:i');
}
$start->addHour();
}
return response()->json($availableHours);
}
public function getSchedule(Request $request, Meja $meja)
{
$date = $request->date;
$reservations = Reservasi::where('meja_id', $meja->id)
->where('date', $date)
->where('status', '!=', 'cancelled')
->get(['start_time', 'end_time']);
return response()->json([
'success' => true,
'reservations' => $reservations
]);
}
public function getAvailableSlots(Request $request)
{
try {
$date = $request->date;
$mejaId = session('selected_meja');
if (!$date || !$mejaId) {
return response()->json([
'status' => 'error',
'error' => 'Data tidak lengkap'
], 400);
}
$meja = Meja::findOrFail($mejaId);
$availableSlots = $meja->getAvailableTimeSlots($date);
// Jika tanggal hari ini, filter slot yang sudah lewat
if ($date === date('Y-m-d')) {
$currentTime = Carbon::now();
$availableSlots = array_filter($availableSlots, function($slot) use ($currentTime) {
return Carbon::parse($slot)->gt($currentTime);
});
}
return response()->json([
'status' => 'success',
'data' => array_values($availableSlots)
]);
} catch (\Exception $e) {
Log::error('Error in getAvailableSlots: ' . $e->getMessage());
return response()->json([
'status' => 'error',
'error' => 'Terjadi kesalahan saat memuat slot waktu'
], 500);
}
}
/**
* Handle Midtrans payment notification
*/
public function handlePaymentNotification(Request $request)
{
try {
$notification = json_decode($request->getContent(), true);
// Get transaction
$transaction = Transaksi::where('transaction_code', $notification['order_id'])->firstOrFail();
$reservasi = $transaction->reservasi;
// Update payment method based on Midtrans payment type
$paymentType = $notification['payment_type'];
switch ($paymentType) {
case 'credit_card':
$paymentMethod = 'credit_card';
break;
case 'bank_transfer':
$vaNumbers = $notification['va_numbers'][0] ?? null;
if ($vaNumbers) {
$bank = strtolower($vaNumbers['bank']);
$paymentMethod = $bank . '_va';
} else {
$paymentMethod = 'other_va';
}
break;
case 'gopay':
$paymentMethod = 'gopay';
break;
case 'shopeepay':
$paymentMethod = 'shopeepay';
break;
case 'qris':
$paymentMethod = 'qris';
break;
case 'cstore':
$store = strtolower($notification['store']);
$paymentMethod = $store;
break;
default:
$paymentMethod = $paymentType;
}
// Update reservation payment method
$reservasi->update([
'payment_method' => $paymentMethod
]);
// Handle transaction status
if ($notification['transaction_status'] == 'capture' || $notification['transaction_status'] == 'settlement') {
$transaction->update(['status' => 'paid']);
$reservasi->update(['status' => 'confirmed']);
} elseif ($notification['transaction_status'] == 'cancel' || $notification['transaction_status'] == 'deny' || $notification['transaction_status'] == 'expire') {
$transaction->update(['status' => 'cancelled']);
$reservasi->update(['status' => 'cancelled']);
}
return response()->json(['status' => 'success']);
} catch (\Exception $e) {
Log::error('Error handling Midtrans notification: ' . $e->getMessage());
return response()->json(['status' => 'error'], 500);
}
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Reservasi;
class RiwayatController extends Controller
{
public function index()
{
// Mengambil semua riwayat pesanan user yang login
$riwayats = Reservasi::where('user_id', auth()->id())
->with(['meja', 'transaksi', 'detailPesanan.menu'])
->orderBy('created_at', 'desc')
->get();
return view('riwayat', compact('riwayats'));
}
public function show($id)
{
// Menampilkan detail riwayat pesanan
$riwayat = Reservasi::with(['meja', 'transaksi', 'detailPesanan.menu'])
->where('user_id', auth()->id())
->findOrFail($id);
// Redirect ke halaman detail transaksi jika ada transaksi
if ($riwayat->transaksi) {
return redirect()->route('transaksi.show', $riwayat->transaksi->id);
}
return view('riwayat.show', compact('riwayat'));
}
public function filter(Request $request)
{
// Validasi input
$request->validate([
'start_date' => 'required|date',
'end_date' => 'required|date|after_or_equal:start_date'
]);
// Filter riwayat berdasarkan tanggal
$riwayats = Reservasi::where('user_id', auth()->id())
->whereBetween('date', [
$request->start_date,
$request->end_date
])
->with(['meja', 'transaksi', 'detailPesanan.menu'])
->orderBy('created_at', 'desc')
->get();
return view('riwayat', compact('riwayats'));
}
}

View File

@ -0,0 +1,444 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Reservasi;
use App\Models\Cart;
use App\Models\Transaksi;
use App\Models\TransaksiItem;
use App\Models\Meja;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
class TransaksiController extends Controller
{
// Menampilkan daftar transaksi
public function index()
{
$transaksi = Transaksi::with(['reservasi'])
->where('user_id', auth()->id())
->orderBy('created_at', 'desc')
->get();
return view('transaksi.index', compact('transaksi'));
}
// Menampilkan halaman transaksi berdasarkan ID reservasi
public function show($id)
{
try {
// Find the transaction with its relationships
$transaksi = Transaksi::with(['reservasi.meja', 'items.menu', 'user'])
->where('user_id', auth()->id())
->findOrFail($id);
if (!$transaksi) {
throw new \Exception('Transaksi tidak ditemukan');
}
$reservasi = $transaksi->reservasi;
if (!$reservasi) {
throw new \Exception('Data reservasi tidak ditemukan');
}
$items = $transaksi->items;
// Get Midtrans snap token if payment is pending
$snapToken = null;
if ($transaksi->status === 'pending') {
$midtransService = new \App\Services\MidtransService();
$snapToken = $midtransService->createTransaction($transaksi);
}
return view('transaksi', compact('transaksi', 'reservasi', 'items', 'snapToken'));
} catch (\Exception $e) {
Log::error('Error in TransaksiController@show: ' . $e->getMessage());
return redirect()->route('menu.index')
->with('error', 'Terjadi kesalahan saat menampilkan transaksi: ' . $e->getMessage());
}
}
// Simpan transaksi
public function store(Request $request)
{
// Debug log
Log::info('Transaksi Request:', $request->all());
// Validasi input
$validated = $request->validate([
'meja_id' => 'required|exists:meja,id',
'tanggal' => 'required|date|after_or_equal:today',
'jam' => 'required|date_format:H:i',
'durasi' => 'required|integer|min:1|max:4',
'jumlah_orang' => 'required|integer|min:1',
'payment_method' => 'required|in:cash,transfer,qris'
]);
DB::beginTransaction();
try {
// Cek ketersediaan meja
$meja = Meja::findOrFail($validated['meja_id']);
if ($meja->status !== 'tersedia') {
return back()->with('error', 'Maaf, meja ini sudah tidak tersedia');
}
// Cek kapasitas meja
if ($validated['jumlah_orang'] > $meja->kapasitas) {
return back()->with('error', 'Jumlah orang melebihi kapasitas meja');
}
// Ambil items dari cart
$cartItems = Cart::where('user_id', auth()->id())
->with('menu')
->get();
Log::info('Cart Items:', $cartItems->toArray());
if ($cartItems->isEmpty()) {
return back()->with('error', 'Keranjang belanja kosong');
}
// Hitung total amount
$totalAmount = $cartItems->sum(function($item) {
return $item->price * $item->quantity;
});
// Generate kode transaksi
$transactionCode = 'TRX-' . date('Ymd') . '-' . strtoupper(uniqid());
// Final amount sama dengan total amount karena tidak ada tax dan service charge
$finalAmount = $totalAmount;
// Buat reservasi
$reservasi = Reservasi::create([
'meja_id' => $meja->id,
'user_id' => auth()->id(),
'date' => $validated['tanggal'],
'start_time' => $validated['jam'],
'end_time' => Carbon::parse($validated['jam'])->addHours($validated['durasi'])->format('H:i'),
'status' => 'pending'
]);
Log::info('Created Reservasi:', $reservasi->toArray());
// Buat transaksi
$transaksi = Transaksi::create([
'transaction_code' => $transactionCode,
'user_id' => auth()->id(),
'reservasi_id' => $reservasi->id,
'total_amount' => $totalAmount,
'final_amount' => $finalAmount,
'status' => 'pending',
'payment_method' => $validated['payment_method']
]);
Log::info('Created Transaksi:', $transaksi->toArray());
// Simpan item transaksi
foreach ($cartItems as $item) {
$transaksiItem = TransaksiItem::create([
'transaksi_id' => $transaksi->id,
'menu_id' => $item->menu_id,
'menu_name' => $item->menu->name,
'quantity' => $item->quantity,
'price' => $item->price,
'subtotal' => $item->subtotal
]);
Log::info('Created TransaksiItem:', $transaksiItem->toArray());
}
// Update status meja
$meja->status = 'dipesan';
$meja->save();
// Hapus cart items
Cart::where('user_id', auth()->id())->delete();
DB::commit();
return redirect()->route('transaksi.show', $transaksi->id)
->with('success', 'Reservasi berhasil dibuat, silahkan lakukan pembayaran');
} catch (\Exception $e) {
DB::rollback();
Log::error('Transaksi Error:', [
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return back()->with('error', 'Terjadi kesalahan saat memproses transaksi: ' . $e->getMessage());
}
}
// Konfirmasi pembayaran
public function confirm(Request $request, $id)
{
DB::beginTransaction();
try {
$transaksi = Transaksi::with('reservasi')->findOrFail($id);
// Pastikan transaksi milik user yang sedang login
if ($transaksi->user_id !== auth()->id()) {
throw new \Exception('Unauthorized access');
}
// Pastikan status transaksi masih pending
if ($transaksi->status !== 'pending') {
throw new \Exception('Transaksi sudah tidak dapat diproses');
}
// Update status transaksi
$transaksi->status = 'paid';
$transaksi->paid_at = now();
$transaksi->save();
// Update status reservasi
if ($transaksi->reservasi) {
$transaksi->reservasi->status = 'confirmed';
$transaksi->reservasi->save();
}
DB::commit();
return redirect()->route('transaksi.show', $id)
->with('success', 'Pembayaran berhasil dikonfirmasi');
} catch (\Exception $e) {
DB::rollback();
Log::error('Error in payment confirmation: ' . $e->getMessage());
return back()->with('error', 'Terjadi kesalahan saat mengkonfirmasi pembayaran: ' . $e->getMessage());
}
}
// Callback untuk Midtrans notification
public function notification(Request $request)
{
try {
$midtransService = new \App\Services\MidtransService();
$notificationData = $midtransService->handleNotification();
Log::info('Processing Midtrans notification', $notificationData);
// Handle order_id with modal suffix
$originalOrderId = preg_replace('/-modal-\d+$/', '', $notificationData['order_id']);
DB::beginTransaction();
$transaksi = Transaksi::where('transaction_code', $originalOrderId)->firstOrFail();
$reservasi = $transaksi->reservasi;
// Get current status to check if we need to update
$currentStatus = $transaksi->status;
$newStatus = null;
switch ($notificationData['transaction_status']) {
case 'capture':
if ($notificationData['payment_type'] == 'credit_card') {
if ($notificationData['fraud_status'] == 'challenge') {
$newStatus = 'pending';
} else {
$newStatus = 'paid';
}
}
break;
case 'settlement':
$newStatus = 'paid';
break;
case 'pending':
$newStatus = 'pending';
break;
case 'deny':
case 'expire':
case 'cancel':
$newStatus = 'cancelled';
break;
}
// Only update if status has changed
if ($newStatus && $currentStatus !== $newStatus) {
Log::info("Updating transaction status from {$currentStatus} to {$newStatus}", [
'transaction_code' => $transaksi->transaction_code
]);
$transaksi->status = $newStatus;
if ($newStatus === 'paid') {
$transaksi->paid_at = now();
if ($reservasi) {
$reservasi->status = 'confirmed';
$reservasi->save();
}
} elseif ($newStatus === 'cancelled') {
if ($reservasi) {
$reservasi->status = 'cancelled';
$reservasi->save();
}
}
$transaksi->save();
}
DB::commit();
return response()->json(['status' => 'success']);
} catch (\Exception $e) {
DB::rollback();
Log::error('Error processing Midtrans notification: ' . $e->getMessage(), [
'trace' => $e->getTraceAsString()
]);
return response()->json([
'status' => 'error',
'message' => 'An error occurred while processing the payment notification'
], 500);
}
}
// Add new method to check payment status
public function checkStatus($id)
{
try {
$transaksi = Transaksi::findOrFail($id);
return response()->json([
'status' => $transaksi->status,
'paid_at' => $transaksi->paid_at ? $transaksi->paid_at->format('Y-m-d H:i:s') : null
]);
} catch (\Exception $e) {
Log::error('Error checking payment status: ' . $e->getMessage());
return response()->json(['error' => 'Failed to check payment status'], 500);
}
}
// Halaman sukses setelah pembayaran
public function finish(Request $request)
{
try {
$order_id = $request->order_id;
$transaksi = Transaksi::where('transaction_code', $order_id)->firstOrFail();
return redirect()->route('transaksi.show', $transaksi->id)
->with('success', 'Pembayaran berhasil diproses');
} catch (\Exception $e) {
Log::error('Payment Finish Error: ' . $e->getMessage());
return redirect()->route('transaksi.index')
->with('error', 'Terjadi kesalahan saat memproses pembayaran');
}
}
// Halaman saat pembayaran tidak berhasil
public function unfinish(Request $request)
{
try {
$order_id = $request->order_id;
$transaksi = Transaksi::where('transaction_code', $order_id)->firstOrFail();
return redirect()->route('transaksi.show', $transaksi->id)
->with('error', 'Pembayaran belum selesai');
} catch (\Exception $e) {
Log::error('Payment Unfinish Error: ' . $e->getMessage());
return redirect()->route('transaksi.index')
->with('error', 'Terjadi kesalahan saat memproses pembayaran');
}
}
// Halaman saat pembayaran error
public function error(Request $request)
{
return redirect()->route('transaksi.index')
->with('error', 'Terjadi kesalahan dalam proses pembayaran');
}
// Menampilkan detail transaksi untuk modal
public function detail($id)
{
try {
// Find the transaction with its relationships and get fresh data
$transaksi = Transaksi::with(['reservasi.meja', 'items.menu', 'user'])
->where('user_id', auth()->id())
->findOrFail($id);
// Refresh the model to get the latest status
$transaksi->refresh();
if (!$transaksi) {
throw new \Exception('Transaksi tidak ditemukan');
}
$reservasi = $transaksi->reservasi;
if (!$reservasi) {
throw new \Exception('Data reservasi tidak ditemukan');
}
$items = $transaksi->items;
// Get Midtrans snap token if payment is pending
$snapToken = null;
if ($transaksi->status === 'pending') {
try {
$midtransService = new \App\Services\MidtransService();
// Add modal suffix to create a unique order ID
$originalCode = $transaksi->transaction_code;
$transaksi->transaction_code = $originalCode . '-modal-' . time();
$snapToken = $midtransService->createTransaction($transaksi);
// Restore original transaction code
$transaksi->transaction_code = $originalCode;
} catch (\Exception $e) {
Log::error('Error creating Midtrans token for modal: ' . $e->getMessage());
// Continue without snap token
}
}
return view('transaksi.detail', compact('transaksi', 'reservasi', 'items', 'snapToken'));
} catch (\Exception $e) {
return response()->json([
'error' => 'Terjadi kesalahan saat menampilkan transaksi: ' . $e->getMessage()
], 500);
}
}
public function cancel(Transaksi $transaksi)
{
try {
// Check if transaction can be cancelled
if ($transaksi->status !== 'pending') {
return redirect()->back()->with('error', 'Hanya transaksi dengan status pending yang dapat dibatalkan.');
}
DB::beginTransaction();
// Update transaction status
$transaksi->update([
'status' => 'cancelled'
]);
// Update reservation status
if ($transaksi->reservasi) {
$transaksi->reservasi->update([
'status' => 'cancelled'
]);
// Update table status if the reservation is for today
if ($transaksi->reservasi->date == now()->format('Y-m-d')) {
$transaksi->reservasi->meja()->update([
'status' => 'tersedia'
]);
}
}
DB::commit();
return redirect()->route('transaksi.show', $transaksi->id)
->with('success', 'Pesanan berhasil dibatalkan.');
} catch (\Exception $e) {
DB::rollback();
Log::error('Error cancelling transaction: ' . $e->getMessage());
return redirect()->back()
->with('error', 'Terjadi kesalahan saat membatalkan pesanan. Silakan coba lagi.');
}
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use App\Models\User;
use Illuminate\Validation\Rules;
class UserProfileController extends Controller
{
public function show()
{
return view('user.profile');
}
public function updateProfile(Request $request)
{
$user = auth()->user();
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,' . $user->id],
'phone' => ['nullable', 'string', 'max:20'],
'profile_picture' => ['nullable', 'image', 'max:2048'], // Max 2MB
]);
if ($request->hasFile('profile_picture')) {
// Delete old profile picture if exists
if ($user->profile_picture) {
Storage::disk('public')->delete($user->profile_picture);
}
// Store new profile picture
$path = $request->file('profile_picture')->store('profile-pictures', 'public');
$validated['profile_picture'] = $path;
}
$user->update($validated);
return back()->with('profile_status', 'Profil berhasil diperbarui!');
}
public function updatePassword(Request $request)
{
$validated = $request->validate([
'current_password' => ['required', 'current_password'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
auth()->user()->update([
'password' => Hash::make($validated['password']),
]);
return back()->with('password_status', 'Password berhasil diperbarui!');
}
public function deleteProfilePicture()
{
$user = auth()->user();
if ($user->profile_picture) {
Storage::disk('public')->delete($user->profile_picture);
$user->update(['profile_picture' => null]);
}
return back()->with('profile_status', 'Foto profil berhasil dihapus!');
}
}

70
app/Http/Kernel.php Normal file
View File

@ -0,0 +1,70 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Cors::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
public function handle(Request $request, Closure $next)
{
if (Auth::check() && Auth::user()->role === 'admin') {
return $next($request);
}
return redirect('/')->with('error', 'Unauthorized access');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
'transaksi/notification/handler',
'*/notification/*',
'transaksi/notification/*'
];
}

13
app/Models/Bestseller.php Normal file
View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Bestseller extends Model
{
use HasFactory;
protected $fillable = ['name', 'image', 'description'];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CarouselImage extends Model
{
use HasFactory;
protected $fillable = [
'image',
'is_active'
];
protected $casts = [
'is_active' => 'boolean'
];
}

44
app/Models/Cart.php Normal file
View File

@ -0,0 +1,44 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Cart extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'menu_id',
'quantity',
'price',
'subtotal',
'notes'
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function menu(): BelongsTo
{
return $this->belongsTo(MenuItem::class, 'menu_id');
}
public static function calculateTotals($items)
{
$subtotal = 0;
foreach ($items as $item) {
$subtotal += ($item->price * $item->quantity);
}
return [
'subtotal' => $subtotal,
'total' => $subtotal
];
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class GalleryCategory extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'thumbnail'
];
public function images()
{
return $this->hasMany(GalleryImage::class, 'category_id');
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class GalleryImage extends Model
{
use HasFactory;
protected $fillable = [
'category_id',
'image',
'caption'
];
public function category()
{
return $this->belongsTo(GalleryCategory::class);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class KritikSaran extends Model
{
use HasFactory;
protected $table = 'kritik_saran';
protected $fillable = [
'user_id',
'nama',
'email',
'jenis',
'pesan'
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

237
app/Models/Meja.php Normal file
View File

@ -0,0 +1,237 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Carbon\Carbon;
class Meja extends Model
{
use HasFactory;
protected $table = 'meja';
protected $fillable = [
'nomor_meja',
'kapasitas',
'status',
'kategori',
'deskripsi',
'gambar'
];
protected $attributes = [
'status' => 'tersedia',
'kategori' => 'outdoor'
];
/**
* Get all reservations for this table.
*/
public function reservasi()
{
return $this->hasMany(Reservasi::class, 'meja_id');
}
/**
* Get active reservations for this table.
*/
public function activeReservations(): HasMany
{
return $this->reservasi()
->where('status', '!=', 'cancelled')
->where('date', '>=', Carbon::today())
->orderBy('date')
->orderBy('start_time');
}
/**
* Check if table has any available slots for a specific date
*/
public function hasAvailableSlotsForDate($date): bool
{
$reservations = $this->getReservationsForDate($date);
$operatingHours = $this->getOperatingHours();
// If no reservations, the entire day is available
if ($reservations->isEmpty()) {
return true;
}
$reservedSlots = $reservations->map(function ($reservation) {
return [
'start' => Carbon::parse($reservation->start_time),
'end' => Carbon::parse($reservation->end_time)
];
})->sortBy('start');
// Check for any gaps between reservations
$previousEnd = Carbon::parse($operatingHours['start']);
foreach ($reservedSlots as $slot) {
if ($previousEnd->lt($slot['start'])) {
return true; // Found a gap
}
$previousEnd = max($previousEnd, $slot['end']);
}
// Check if there's time after the last reservation
$lastSlotEnd = $reservedSlots->last()['end'];
$closingTime = Carbon::parse($operatingHours['end']);
return $lastSlotEnd->lt($closingTime);
}
/**
* Get the next available date with open slots
*/
public function getNextAvailableDate($startDate = null): ?string
{
$date = $startDate ? Carbon::parse($startDate) : Carbon::today();
$maxDays = 30; // Limit search to next 30 days
$daysChecked = 0;
while ($daysChecked < $maxDays) {
if ($this->hasAvailableSlotsForDate($date->format('Y-m-d'))) {
return $date->format('Y-m-d');
}
$date->addDay();
$daysChecked++;
}
return null;
}
/**
* Get operating hours
*/
public function getOperatingHours(): array
{
return [
'start' => '10:00',
'end' => '22:00'
];
}
/**
* Get available time slots for a specific date
*/
public function getAvailableTimeSlots($date): array
{
$reservations = $this->getReservationsForDate($date);
$operatingHours = $this->getOperatingHours();
$slots = [];
$startTime = Carbon::parse($operatingHours['start']);
$endTime = Carbon::parse($operatingHours['end']);
$interval = 30; // 30 minutes interval
// If date is today, start from current time rounded up to next 30 minutes
if ($date === date('Y-m-d')) {
$now = Carbon::now();
$startTime = $now->copy()->addMinutes($interval - ($now->minute % $interval))->startOfMinute();
if ($startTime->lt($now)) {
$startTime->addMinutes($interval);
}
}
while ($startTime < $endTime) {
$timeSlot = $startTime->format('H:i');
$isAvailable = true;
// Check if this time slot conflicts with any existing reservations
foreach ($reservations as $reservation) {
$reservationStart = Carbon::parse($reservation->start_time);
$reservationEnd = Carbon::parse($reservation->end_time);
if ($startTime->between($reservationStart, $reservationEnd, true)) {
$isAvailable = false;
break;
}
}
if ($isAvailable) {
$slots[] = $timeSlot;
}
$startTime->addMinutes($interval);
}
return $slots;
}
/**
* Get reservations for a specific date
*/
public function getReservationsForDate($date)
{
return $this->reservasi()
->whereDate('date', $date)
->where('status', '!=', 'cancelled')
->get(['start_time', 'end_time']);
}
/**
* Check if table is available for a specific time slot.
*/
public function isAvailableForTimeSlot($date, $startTime, $endTime): bool
{
return Reservasi::isTimeSlotAvailable($this->id, $date, $startTime, $endTime);
}
/**
* Get the status badge class
*/
public function getStatusBadgeClass(): string
{
return match($this->status) {
'tersedia' => 'bg-green-100 text-green-800',
'dipesan' => 'bg-yellow-100 text-yellow-800',
'terisi' => 'bg-red-100 text-red-800',
default => 'bg-gray-100 text-gray-800',
};
}
/**
* Get formatted category name
*/
public function getFormattedCategory(): string
{
return match($this->kategori) {
'outdoor' => 'Outdoor',
'vip-outdoor' => 'VIP Outdoor',
'vip-indoor' => 'VIP Indoor',
default => ucfirst($this->kategori),
};
}
/**
* Check if the table is available
*/
public function getIsAvailableAttribute(): bool
{
return $this->status === 'tersedia';
}
/**
* Format nomor meja for display
*/
public function getNomorMejaFormattedAttribute(): string
{
return 'M' . str_pad($this->nomor_meja, 3, '0', STR_PAD_LEFT);
}
// Accessor untuk memastikan kapasitas selalu integer
public function getKapasitasAttribute($value)
{
return (int) $value;
}
// Scope untuk meja yang tersedia
public function scopeAvailable($query)
{
return $query->where('status', 'tersedia');
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class MenuCategory extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function menuItems(): HasMany
{
return $this->hasMany(MenuItem::class, 'category_id');
}
}

26
app/Models/MenuItem.php Normal file
View File

@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class MenuItem extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'price',
'image',
'category_id',
'is_available'
];
public function category(): BelongsTo
{
return $this->belongsTo(MenuCategory::class, 'category_id');
}
}

192
app/Models/Reservasi.php Normal file
View File

@ -0,0 +1,192 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Carbon\Carbon;
class Reservasi extends Model
{
use HasFactory;
protected $table = 'reservasi';
protected $fillable = [
'user_id',
'meja_id',
'name',
'phone',
'date',
'start_time',
'status',
'notes',
'total_harga',
'payment_method'
];
protected $casts = [
'date' => 'date',
'start_time' => 'datetime:H:i',
];
const STATUS_PENDING = 'pending';
const STATUS_CONFIRMED = 'confirmed';
const STATUS_COMPLETED = 'completed';
const STATUS_CANCELLED = 'cancelled';
/**
* Get the user that owns the reservation.
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Get the table that is reserved.
*/
public function meja(): BelongsTo
{
return $this->belongsTo(Meja::class, 'meja_id');
}
/**
* Get the transaction associated with the reservation.
*/
public function transaksi(): HasOne
{
return $this->hasOne(Transaksi::class);
}
/**
* Get the transaction items through the transaction.
*/
public function detailPesanan(): HasManyThrough
{
return $this->hasManyThrough(
TransaksiItem::class,
Transaksi::class,
'reservasi_id', // Foreign key on transaksi table...
'transaksi_id', // Foreign key on transaksi_items table...
'id', // Local key on reservasi table...
'id' // Local key on transaksi table...
);
}
/**
* Check if a time slot is available for a specific table.
*/
public static function isTimeSlotAvailable($mejaId, $date, $startTime): bool
{
// Convert times to Carbon instances for comparison
$start = Carbon::parse($startTime);
$requestedDate = Carbon::parse($date);
// Check if the requested date and time is in the past
if ($requestedDate->isPast() && $requestedDate->isToday() && $start->isPast()) {
return false;
}
// Check for existing reservations at the same time slot
$conflictingReservations = self::where('meja_id', $mejaId)
->whereDate('date', $date)
->whereNotIn('status', [self::STATUS_CANCELLED])
->where('start_time', $startTime)
->exists();
return !$conflictingReservations;
}
/**
* Get all available time slots for a specific table and date
*/
public static function getAvailableTimeSlots($mejaId, $date)
{
// Get all reservations for this table on this date
$reservations = self::where('meja_id', $mejaId)
->whereDate('date', $date)
->whereNotIn('status', [self::STATUS_CANCELLED])
->get(['start_time']);
$timeSlots = [];
$startHour = 10; // 10:00
$endHour = 22; // 22:00
$interval = 30; // 30 minutes interval
for ($hour = $startHour; $hour < $endHour; $hour++) {
for ($minute = 0; $minute < 60; $minute += $interval) {
$currentTime = sprintf('%02d:%02d', $hour, $minute);
// Check if this time slot is available
if (self::isTimeSlotAvailable($mejaId, $date, $currentTime)) {
$timeSlots[] = [
'start_time' => $currentTime,
'is_available' => true
];
}
}
}
// If date is today, remove past time slots
if ($date == Carbon::today()->format('Y-m-d')) {
$currentTime = Carbon::now();
$timeSlots = array_filter($timeSlots, function($slot) use ($currentTime) {
return Carbon::parse($slot['start_time'])->gt($currentTime);
});
}
return array_values($timeSlots);
}
/**
* Update table status based on reservation status
*/
public function updateTableStatus()
{
if ($this->date == now()->format('Y-m-d')) {
$status = match($this->status) {
self::STATUS_CONFIRMED => 'dipesan',
self::STATUS_COMPLETED, self::STATUS_CANCELLED => 'tersedia',
default => null
};
if ($status) {
$this->meja()->update(['status' => $status]);
}
}
}
/**
* Get payment method display name
*/
public function getPaymentMethodDisplayAttribute()
{
$methods = [
'credit_card' => 'Kartu Kredit',
'mandiri_clickpay' => 'Mandiri Clickpay',
'cimb_clicks' => 'CIMB Clicks',
'bca_klikbca' => 'BCA KlikBCA',
'bca_klikpay' => 'BCA KlikPay',
'bri_epay' => 'BRI e-Pay',
'echannel' => 'Mandiri Bill Payment',
'permata_va' => 'Permata Virtual Account',
'bca_va' => 'BCA Virtual Account',
'bni_va' => 'BNI Virtual Account',
'bri_va' => 'BRI Virtual Account',
'other_va' => 'Virtual Account Bank Lain',
'gopay' => 'GoPay',
'shopeepay' => 'ShopeePay',
'qris' => 'QRIS',
'indomaret' => 'Indomaret',
'alfamart' => 'Alfamart',
'danamon_online' => 'Danamon Online Banking',
'akulaku' => 'Akulaku'
];
return $methods[$this->payment_method] ?? $this->payment_method;
}
}

51
app/Models/Transaksi.php Normal file
View File

@ -0,0 +1,51 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Transaksi extends Model
{
use HasFactory;
// Nama tabel, jika tidak sesuai dengan nama default
protected $table = 'transaksi';
// Kolom yang dapat diisi
protected $fillable = [
'transaction_code',
'user_id',
'reservasi_id',
'total_amount',
'final_amount',
'status',
'payment_method',
'payment_proof',
'paid_at',
'notes'
];
protected $casts = [
'paid_at' => 'datetime'
];
// Relasi dengan model User
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
// Relasi dengan model Reservasi
public function reservasi(): BelongsTo
{
return $this->belongsTo(Reservasi::class);
}
// Relasi dengan model TransaksiItem
public function items(): HasMany
{
return $this->hasMany(TransaksiItem::class);
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class TransaksiItem extends Model
{
use HasFactory;
protected $table = 'transaksi_items';
protected $fillable = [
'transaksi_id',
'menu_id',
'menu_name',
'quantity',
'price',
'subtotal',
'notes'
];
// Relasi dengan model Transaksi
public function transaksi(): BelongsTo
{
return $this->belongsTo(Transaksi::class, 'transaksi_id');
}
// Relasi dengan model Menu
public function menu(): BelongsTo
{
return $this->belongsTo(MenuItem::class, 'menu_id');
}
}

62
app/Models/User.php Normal file
View File

@ -0,0 +1,62 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'phone',
'address',
'birth_date',
'gender',
'profile_picture',
'role'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'birth_date' => 'date',
];
public function isAdmin()
{
return $this->role === 'admin';
}
public function sendPasswordResetNotification($token)
{
$this->notify(new \App\Notifications\ResetPasswordNotification($token, $this->email));
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Lang;
class ResetPasswordNotification extends Notification
{
use Queueable;
public $token;
public $email;
public function __construct($token, $email)
{
$this->token = $token;
$this->email = $email;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
$url = url(route('password.reset', [
'token' => $this->token,
'email' => $this->email,
], false));
return (new MailMessage)
->subject(Lang::get('Reset Password Notification'))
->view('emails.reset-password', ['url' => $url]);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;
class AppLayoutServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
Blade::component('app-layout', \App\View\Components\AppLayout::class);
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
//
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to your application's "home" route.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/menu';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace App\Services;
use Midtrans\Config;
use Midtrans\Snap;
use Midtrans\Notification;
use App\Models\Transaksi;
use Illuminate\Support\Facades\Log;
class MidtransService
{
public function __construct()
{
// Set Midtrans configuration
Config::$serverKey = config('midtrans.server_key');
Config::$clientKey = config('midtrans.client_key');
Config::$isProduction = config('midtrans.is_production');
Config::$isSanitized = config('midtrans.is_sanitized');
Config::$is3ds = config('midtrans.is_3ds');
// Set append notification URL
Config::$appendNotifUrl = route('transaksi.notification');
// Set overrideNotifUrl if in development
if (!config('midtrans.is_production') && config('midtrans.notification_url')) {
Config::$overrideNotifUrl = config('midtrans.notification_url');
}
}
public function createTransaction(Transaksi $transaksi)
{
try {
$items = [];
foreach ($transaksi->items as $item) {
$items[] = [
'id' => $item->menu_id,
'price' => (int)$item->price,
'quantity' => (int)$item->quantity,
'name' => $item->menu_name
];
}
$transaction_details = [
'order_id' => $transaksi->transaction_code,
'gross_amount' => (int)$transaksi->final_amount,
];
$customer_details = [
'first_name' => $transaksi->user->name,
'email' => $transaksi->user->email,
'phone' => $transaksi->user->phone ?? '',
];
$enable_payments = [
"credit_card", "gopay", "shopeepay", "bca_va", "bni_va", "bri_va",
"echannel", "permata_va", "other_va", "qris"
];
$transaction_data = [
'transaction_details' => $transaction_details,
'item_details' => $items,
'customer_details' => $customer_details,
'enable_payments' => $enable_payments,
'callbacks' => [
'finish' => route('transaksi.finish') . '?order_id=' . $transaksi->transaction_code,
'error' => route('transaksi.error') . '?order_id=' . $transaksi->transaction_code,
'unfinish' => route('transaksi.unfinish') . '?order_id=' . $transaksi->transaction_code
]
];
Log::info('Creating Midtrans transaction', [
'transaction_code' => $transaksi->transaction_code,
'amount' => $transaksi->final_amount,
'customer' => $customer_details
]);
$snapToken = Snap::getSnapToken($transaction_data);
Log::info('Midtrans snap token created', [
'transaction_code' => $transaksi->transaction_code,
'snap_token' => $snapToken
]);
return $snapToken;
} catch (\Exception $e) {
Log::error('Error creating Midtrans transaction', [
'error' => $e->getMessage(),
'transaction_code' => $transaksi->transaction_code ?? null
]);
throw new \Exception('Error creating Midtrans transaction: ' . $e->getMessage());
}
}
public function handleNotification($rawNotification = null)
{
try {
$notification = $rawNotification ?? new Notification();
Log::info('Handling Midtrans notification', [
'order_id' => $notification->order_id,
'transaction_status' => $notification->transaction_status,
'payment_type' => $notification->payment_type,
'fraud_status' => $notification->fraud_status ?? null
]);
return [
'order_id' => $notification->order_id,
'transaction_status' => $notification->transaction_status,
'payment_type' => $notification->payment_type,
'fraud_status' => $notification->fraud_status ?? null,
'gross_amount' => $notification->gross_amount,
'signature_key' => $notification->signature_key
];
} catch (\Exception $e) {
Log::error('Error handling Midtrans notification', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
throw $e;
}
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class AppLayout extends Component
{
public function __construct()
{
//
}
public function render()
{
return view('components.app-layout');
}
}

53
artisan Normal file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any of our classes manually. It's great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php Normal file
View File

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

68
composer.json Normal file
View File

@ -0,0 +1,68 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.1",
"guzzlehttp/guzzle": "^7.9",
"laravel/framework": "^10.10",
"laravel/sanctum": "^3.3",
"laravel/tinker": "^2.8",
"midtrans/midtrans-php": "^2.6",
"phpmailer/phpmailer": "^6.10"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.18",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^7.0",
"phpunit/phpunit": "^10.1",
"spatie/laravel-ignition": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8275
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

189
config/app.php Normal file
View File

@ -0,0 +1,189 @@
<?php
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\ServiceProvider;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\AppLayoutServiceProvider::class,
])->toArray(),
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'Example' => App\Facades\Example::class,
])->toArray(),
];

115
config/auth.php Normal file
View File

@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

71
config/broadcasting.php Normal file
View File

@ -0,0 +1,71 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

111
config/cache.php Normal file
View File

@ -0,0 +1,111 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
| stores there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

34
config/cors.php Normal file
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

151
config/database.php Normal file
View File

@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

76
config/filesystems.php Normal file
View File

@ -0,0 +1,76 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been set up for each driver as an example of the required values.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

54
config/hashing.php Normal file
View File

@ -0,0 +1,54 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 12),
'verify' => true,
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 65536,
'threads' => 1,
'time' => 4,
'verify' => true,
],
];

131
config/logging.php Normal file
View File

@ -0,0 +1,131 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => LOG_USER,
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

134
config/mail.php Normal file
View File

@ -0,0 +1,134 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "log", "array", "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => null,
// 'client' => [
// 'timeout' => 5,
// ],
],
'mailgun' => [
'transport' => 'mailgun',
// 'client' => [
// 'timeout' => 5,
// ],
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

28
config/midtrans.php Normal file
View File

@ -0,0 +1,28 @@
<?php
return [
'merchant_id' => env('MIDTRANS_MERCHANT_ID', ''),
'client_key' => env('MIDTRANS_CLIENT_KEY', ''),
'server_key' => env('MIDTRANS_SERVER_KEY', ''),
'is_production' => env('MIDTRANS_IS_PRODUCTION', true),
'is_sanitized' => env('MIDTRANS_IS_SANITIZED', true),
'is_3ds' => env('MIDTRANS_IS_3DS', true),
// Base URL for API requests
'base_url' => env('MIDTRANS_IS_PRODUCTION', true) ?
'https://api.midtrans.com' :
'https://api.sandbox.midtrans.com',
// Notification URL
'notification_url' => env('MIDTRANS_NOTIFICATION_URL'),
// Default currency
'currency' => env('MIDTRANS_CURRENCY', 'IDR'),
// Payment methods to enable (empty array means all available methods)
'enabled_payments' => [],
// Default language
'language' => env('MIDTRANS_LANGUAGE', 'id'),
];

109
config/queue.php Normal file
View File

@ -0,0 +1,109 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

83
config/sanctum.php Normal file
View File

@ -0,0 +1,83 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
],
];

34
config/services.php Normal file
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
'scheme' => 'https',
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

214
config/session.php Normal file
View File

@ -0,0 +1,214 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => false,
];

36
config/view.php Normal file
View File

@ -0,0 +1,36 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];

1
database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite*

View File

@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View File

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('menu_categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('menu_categories');
}
};

View File

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('menu_items', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->decimal('price', 10, 2);
$table->string('image');
$table->foreignId('category_id')->constrained('menu_categories')->onDelete('cascade');
$table->boolean('is_available')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('menu_items');
}
};

View File

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('meja', function (Blueprint $table) {
$table->id();
$table->string('nomor_meja')->unique();
$table->integer('kapasitas');
$table->enum('status', ['tersedia', 'dipesan', 'terisi'])->default('tersedia');
$table->enum('kategori', ['outdoor', 'vip-outdoor', 'vip-indoor'])->default('outdoor');
$table->text('deskripsi')->nullable();
$table->string('gambar')->nullable(); // Kolom untuk menyimpan path gambar
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('meja');
}
};

View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('reservasi', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('meja_id')->constrained('meja')->onDelete('cascade');
$table->string('name');
$table->string('phone');
$table->date('date');
$table->time('start_time');
$table->decimal('total_harga', 10, 2)->default(0);
$table->enum('payment_method', [
'credit_card',
'mandiri_clickpay',
'cimb_clicks',
'bca_klikbca',
'bca_klikpay',
'bri_epay',
'echannel',
'permata_va',
'bca_va',
'bni_va',
'bri_va',
'other_va',
'gopay',
'shopeepay',
'qris',
'indomaret',
'alfamart',
'danamon_online',
'akulaku'
])->nullable();
$table->enum('status', ['pending', 'confirmed', 'completed', 'cancelled'])->default('pending');
$table->text('notes')->nullable();
$table->timestamps();
// Add index for common queries
$table->index(['meja_id', 'date', 'status']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('reservasi');
}
};

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('transaksi', function (Blueprint $table) {
$table->id();
$table->string('transaction_code')->unique();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('reservasi_id')->nullable()->constrained('reservasi')->onDelete('set null');
$table->decimal('total_amount', 10, 2);
$table->decimal('final_amount', 10, 2);
$table->enum('status', ['pending', 'paid', 'cancelled'])->default('pending');
$table->enum('payment_method', ['cash', 'transfer', 'qris'])->nullable();
$table->string('payment_proof')->nullable();
$table->timestamp('paid_at')->nullable();
$table->text('notes')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('transaksi');
}
};

View File

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('transaksi_items', function (Blueprint $table) {
$table->id();
$table->foreignId('transaksi_id')->constrained('transaksi')->onDelete('cascade');
$table->foreignId('menu_id')->constrained('menu_items')->onDelete('cascade');
$table->string('menu_name');
$table->integer('quantity');
$table->decimal('price', 10, 2);
$table->decimal('subtotal', 10, 2);
$table->string('notes')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('transaksi_items');
}
};

View File

@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('kritik_saran', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->nullable()->constrained('users')->onDelete('cascade');
$table->string('nama');
$table->string('email');
$table->enum('jenis', ['kritik', 'saran']);
$table->text('pesan');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('kritik_saran');
}
};

Some files were not shown because too many files have changed in this diff Show More