Welcome back to the Laravel E-Commerce Project Tutorial. In this tutorial, we are going to learn about user order cancellation.
Step 1: Add a Form to the Order Details Page
First, let's go to the order-details.blade.php file and add a form:
<div class="wg-box 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="submit" class="btn btn-danger">Cancel Order</button>
</form>
</div>
Step 2: Create a Function in UserController
Now, let's go to the UserController and create a function:
public function account_cancel_order(Request $request)
{
$order = Order::find($request->order_id);
$order->status = "canceled";
$order->canceled_date = Carbon::now();
$order->save();
return back()->with("status", "Order has been cancelled successfully!");
}
Step 3: Create a Route for the Function
Next, let's create a route for this function. Go to the web.php file and create a new route:
Route::put('/account-order/cancel-order',[UserController::class,'account_cancel_order'])->name('user.account_cancel_order');
Step 4: Update the Order Details Page
Now, let's go back to the order-details.blade.php file and update it. Add the action `action="{{route('user.account_cancel_order')}}"` and also add the `@csrf` and `@method` directives with the `PUT` method.
For displaying the confirmation message, add:
@if(Session::has('status'))
<p class="alert alert-success">{{Session::get('status')}}</p>
@endif
Testing the Order Cancellation
Now, let's check. Refresh the page, go to the orders page, and click on the order details link. You can see the order cancel button. Click on this button, and you can see that the order has been cancelled.
In this way, you can give the option to users to cancel their orders.
That's all about user order cancellation.