Laravel E-Commerce Project - Wishlist Using Database
In this video, we will learn how to create a wishlist using a database.
Currently, we are using a session to store wishlist items. However, this means that if we add a product to the wishlist and then log out, the wishlist will be empty when we log back in.
Let's explore how to store wishlist items in a table so that they are not removed even after logging out. In a previous tutorial, we created a migration for the cart. We can use this same migration to store wishlist items.
To do this, go to the ShopComponent.php class file and inside the render method, add the following code:
if(Auth::check())
{
Cart::instance('cart')->store(Auth::user()->email);
Cart::instance('wishlist')->store(Auth::user()->email);
}
Next, to restore the wishlist, go to the HomeComponent.php class file and inside the render method, write the following code:
if(Auth::check())
{
Cart::instance('cart')->restore(Auth::user()->email);
Cart::instance('wishlist')->restore(Auth::user()->email);
}
That's it! Save the files and let's test the functionality.
Switch to the browser and refresh the page. Log in with your user credentials and add some items to the wishlist. After adding products to the wishlist, log out. You will see that the wishlist is empty.
Now, log in again with the same user credentials. You will see that all the wishlist items are restored.
In this way, you can create a wishlist using a database.