...

/

Completion of the Order

Completion of the Order

Time to complete our exercise and review what we have covered so far.

Done with the dinner

Once the customer is done with the order, the user can complete it and accept the payment. To keep things simple in this exercise, we will not worry about the payments. Instead, we will focus on completing an order and making the table available again for future orders.

<?php

namespace App\Http\Controllers;

use App\Http\Resources\OrderResource;
use App\Models\Order;
use App\Models\Table;
use App\ModelStates\Table\Available;
use App\ModelStates\Table\Occupied;

class OrderController extends Controller
{
    public function listOpen(): array
    {
        $orders = Order::with('table')
            ->where('restaurant_id', request('restaurant_id'))
            ->open()
            ->get();

        return [
            'orders' => OrderResource::collection($orders),
        ];
    }

    public function listCompleted(): array
    {
        $orders = Order::with('table')
            ->where('restaurant_id', request('restaurant_id'))
            ->completed()
            ->get();

        return [
            'orders' => OrderResource::collection($orders),
        ];
    }

    public function bookATable(int $tableId): array
    {
        $table = Table::where('restaurant_id', request('restaurant_id'))
            ->where('id', $tableId)
            ->firstOrFail();

        $table->changeStatusTo(Occupied::class);

        $order = Order::create([
            'restaurant_id' => request('restaurant_id'),
            'table_id' => $table->id,
        ]);

        return [
            'order_id' => $order->id,
        ];
    }

    public function details(int $orderId): array
    {
        $order = Order::with(['table', 'items', 'items.menuItem'])
            ->where('restaurant_id', request('restaurant_id'))
            ->findOrFail($orderId);

        return [
            'order' => new OrderResource($order),
        ];
    }

    public function complete(int $orderId): void
    {
        $order = Order::with('table')
            ->where('restaurant_id', request('restaurant_id'))
            ->where('id', $orderId)
            ->firstOrFail();

        $order->table->changeStatusTo(Available::class);
        $order->update([
            'completed_at' => now(),
        ]);
    }
}

Import the CompleteOrder.json file. Restaurant API collection and all the API requests covered so far ...