Laravel 12 E-Commerce Project Tutorial

User: Implementing Order Cancellation Logic

Hi everyone, welcome back to the Laravel E-Commerce Project Tutorial. This video focuses on implementing the functionality for the User to cancel an order directly from their account dashboard, specifically on the order details page.

  1. Add the Cancel Button to `order-details.blade.php`

    Open the user's`order-details.blade.php` view. Add a conditional form that displays the Cancel Order button only if the order status is currently `"ordered"` (meaning it has not been delivered or canceled yet).

    @if ($order->status == "ordered")
    <div class="card-body mt-5 text-right">
    <form action="{{ route("user.account_cancel_order") }}" method="POST">
    @csrf
    @method("PUT")
    <input type="hidden" name="order_id" value="{{ $order->id }}" />
    <button type="button" class="btn btn-danger cancel-order-btn-sm">Cancel Order</button>
    </form>
    </div>
    @endif
  2. Create the `account_cancel_order` Function in `UserController`

    In your `UserController`, implement the function to handle the cancellation request. This function updates the order status to `"canceled"` and records the cancellation date.

    use CarbonCarbon; // Ensure Carbon is included at the top
    public function account_cancel_order(Request $request)
    {
    // Find the order by ID
    $order = Order::find($request->order_id);

    // Check if the order status allows cancellation (optional security check, but good practice)
    // if ($order && $order->status == "ordered") {
    $order->status = "canceled";
    $order->canceled_date = Carbon::now();
    $order->save();
    return back()->with("status", "Order has been cancelled successfully!");
    // }
    // return back()->with("error", "Order cannot be cancelled.");
    }
  3. Define the Route for Cancellation

    Add the following PUT route to your `web.php` file for handling the form submission:

    Route::put("/account-order/cancel-order",[UserController::class,"account_cancel_order"])->name("user.account_cancel_order");
  4. Display the Success Message

    In `order-details.blade.php`, ensure there is a section to display the status flash message after a successful cancellation:

    <div class="col-lg-10">
    @if (Session::has("status"))
    <p class="alert alert-success">{{ Session::get("status") }}</p>
    @endif
    <div class="wg-box mt-5 mb-5">
    <div class="row">
    <div class="col-6">
    <h5>Ordered Details</h5>
    <!-- ... other details ... -->

Verification and Testing ❌

1. Log into a user account and navigate to an order'sdetails page that has the status Ordered.
2. Click the Cancel Order button.
3. Verify that the order status is updated to Canceled, a success message is displayed, and the Cancel Order button is no longer visible.