Laravel E-Commerce Project - Store And Display Product Attributes With Order
In this video, we will learn how to store and display product attributes with orders.
First, let's add a column to the order_items table to store the product attributes details. Switch to the command prompt and run the command:
php artisan make:migration add_options_to_order_items_table –table=order_items
Next, open the migration file and add a column:
public function up()
{
Schema::table('order_items', function (Blueprint $table) {
$table->longText('options')->nullable();
});
}
public function down()
{
Schema::table('order_items', function (Blueprint $table) {
$table->dropColumn('options');
});
}
Save the changes and migrate the migration. Switch to the command prompt and run the command:
php artisan migrate
Now, run the application:
php artisan serve
Open the CheckoutComponent.php class file and store the product attributes inside the placeOrder function:
if($item->options)
{
$orderItem->options = serialize($item->options);
}
That's it! Let's test the functionality. Add a product to the cart, checkout, and place an order. You should see the message "Order placed successfully".
Now, let's check the database. Open phpMyAdmin, browse the order_items table, and you should see the ordered items with attributes values.
Next, let's display the order attributes on the user's order details page. Open the user-order-details-component.blade.php view file and add the following code:
@if($item->options)
<div class="product-name">
@foreach(unserialize($item->options) as $key => $value)
<p><b>{{$key}}:{{$value}}</b></p>
@endforeach
</div>
@endif
Save the changes and refresh the page. Go to "My Orders" and view the details of the order. You should see the product attributes.
Now, let's display the product attributes on the admin's order details page. Open the admin-order-details-component.blade.php view file and add the following code:
@if($item->options)
<div class="product-name">
@foreach(unserialize($item->options) as $key => $value)
<p><b>{{$key}}:{{$value}}</b></p>
@endforeach
</div>
@endif
Save the changes and refresh the page. Logout from the user account, login with admin credentials, and go to the "All Orders" page. Open the order details page, and you should see the product attributes.
By following these steps, you can store and display product attributes with orders.