How to make wishlist in laravel 5.5

How to make wishlist in laravel 5.5

3,852

Today I'm going to teach you how to make wish list (favorite) with Laravel 5.5.X.

Before we start here is what we will have at the end of this tutorial:


We will achieve

Simple add button

Only allow logged users to add items to wish list

Avoid duplicate data insert

 

I assume you have laravel installed on your system.

Lets begin

Make wish list controller

php artisan make:controller WishlistController --resource
PHP

Make Model and Migration for wishlist

php artisan make:model Wishlist -m
PHP

Go to your Database->migrations and open your latest migration which is something like:

2017_11_01_121928_create_wishlists_table.php
PHP

Here we need to get user_id and product_id here is how we'll do it.

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateWishlistsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('wishlists', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->timestamps();
        });

        Schema::table(&#39;wishlists&#39;, function($table) {
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('product_id')->references('id')->on('products');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('wishlists');
    }
}
PHP

Now make your table

php artisan migrate
PHP

Now our database is set let's setup our models

Open Wishlist model and add this lines

    protected $table = "wishlists";

    public function user(){
       return $this->belongsTo(User::class);
    }

    public function product(){
       return $this->belongsTo(Product::class);
    }
PHP

In your User model add:

public function wishlist(){
       return $this->hasMany(Wishlist::class);
    }
PHP

And in your Product model add:

public function wishlist(){
     return $this->hasMany(Wishlist::class);
  }
PHP

Let make our routes

Open web.php in routes folder and add recource url for WishlistController

Route::resource('/wishlist', 'WishlistController', ['except' => ['create', 'edit', 'show', 'update']]);
PHP

As you see I excepted create edit show and update  because we not going to need those.

Controller settings

Open your wishlist controller

Add in top of your file

use AppWishlist;
use Auth;
PHP

Add __construct to your controller to access only logged users to make wish list:

public function __construct() {
        $this->middleware(['auth']);
    }
PHP

Index function:

public function index()
    {
      $user = Auth::user();
      $wishlists = Wishlist::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10);
      return view('frontend.wishlist', compact('user', 'wishlists'));
    }
PHP

Here $user = Auth::user(); we will get user id with Auth to get the right user id.

Here $wishlists We get user id with Auth to only return list of each user wish lists to them and not wish lists of another users! and order it by latest add item to the first.

Store function:

public function store(Request $request)
    {
//Validating title and body field
      $this->validate($request, array(
          'user_id'=>'required',
          'product_id' =>'required',
        ));

      $wishlist = new Wishlist;

      $wishlist->user_id = $request->user_id;
      $wishlist->product_id = $request->product_id;


      $wishlist->save();

      return redirect()->back()->with('flash_message',
          'Item, '. $wishlist->product->title.' Added to your wishlist.');
}
PHP

In this method we will get user_id and product_id in Front-End and save it as new row in wishlists table.

Destroy function:

public function destroy($id)
    {
      $wishlist = Wishlist::findOrFail($id);
      $wishlist->delete();

      return redirect()->route('wishlist.index')
          ->with('flash_message',
           'Item successfully deleted');
    }
PHP

Our job here is done! all we need now is to add button in Front-End to collect information and save it to database.

Create Submit button

<form action="{{route('wishlist.store')}}" id="contact_form" method="post">
  {{csrf_field()}}
  <input name="user_id" type="text" value="{{Auth::user()->id}}" />
  <input name="product_id" type="text" value="{{$product->id}}" />
</form>
HTML

Add this form everywhere (in your single product blade) you want to show button.

Avoid duplicate

If you want to each user only save each product one time (unless they've deleted that product from their wishlists before) just change your store function with code below

public function store(Request $request)
    {
$this->validate($request, array(
 'user_id'=>'required',
 'product_id' =>'required',
));

$status=Wishlist::where('user_id',Auth::user()->id)
->where('product_id',$request->product_id)
->first();

if(isset($status->user_id) and isset($request->product_id))
   {
       return redirect()->back()->with('flash_messaged', 'This item is already in your 
       wishlist!');
   }
   else
   {
       $wishlist = new Wishlist;

       $wishlist->user_id = $request->user_id;
       $wishlist->product_id = $request->product_id;
       $wishlist->save();

       return redirect()->back()->with('flash_message',
                     'Item, '. $wishlist->product->title.' Added to your wishlist.');
   }

}
PHP

 

Article Update:

Thanks to social media feedback and comments on this post I think I should update this post and make clear some parts.

1) How to make wishlists index file?

Well, as I mentioned above we have index function in our WishlistController and there we return view frontend.wishlist you can address it everywhere you like as long as it is in your views folder. In wishlist.blade.php all you need to do is to foreach your wishlists like: @foreach ($wishlists as $wishlist) ….. @endforeach .

But to make it clear and show each user only their wishlists and not other users we need condition before our foreach which we will make it like: @if (Auth::user()->wishlist->count() )
Here is complete code:


@if (Auth::user()->wishlist->count() )
@foreach ($wishlists as $wishlist)
{{$wishlist->product->title}}
@endforeach
@endif

PHP

2) Getting foreign key?

As you see in order to make wishlist we need to integer id's user_id which will be create when we install auth and product_id that means you must have products table before creating wishlist table, otherwise you will get error that defines there is no product id.

If you don't have have products table make that first and then follow this tutorial

But if you already followed this tutorial and just now you want to make products table no problem! just add your migration


php artisan make:model Product -m

PHP

And in your migrations folder (under database folder) change the timestamp of your file to time before your wishlist migration

Here is example

// Wishlist migration

2017_10_15_122736_create_wishlistss_table.php


//products migration

2017_10_17_092716_create_products_table.php
PHP

Change it to

// Wishlist migration

2017_10_15_122736_create_wishlistss_table.php

//products migration

2017_10_14_092716_create_products_table.php
PHP

As you see I changed the date of products from 17 Oct 2017 to 14 Oct 2017 which is one day before our wishlists migration dates (it could be even 1 sec before it, all it matters is to timing be before wishlist.)

 

What do you think about this article? share your opinion with us, Leave a comment.

- Last updated 4 years ago

Be the first to leave a comment.

You must login to leave a comment