
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
Make Model
and Migration
for wishlist
php artisan make:model Wishlist -m
Go to your Database->migrations
and open your latest migration which is something like:
2017_11_01_121928_create_wishlists_table.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('wishlists', 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');
}
}
Now make your table
php artisan migrate
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);
}
In your User model
add:
public function wishlist(){
return $this->hasMany(Wishlist::class);
}
And in your Product model
add:
public function wishlist(){
return $this->hasMany(Wishlist::class);
}
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']]);
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;
Add __construct
to your controller to access only logged users to make wish list:
public function __construct() {
$this->middleware(['auth']);
}
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'));
}
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.');
}
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');
}
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>
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.');
}
}
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
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
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
Change it to
// Wishlist migration
2017_10_15_122736_create_wishlistss_table.php
//products migration
2017_10_14_092716_create_products_table.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 5 years ago
Be the first to leave a comment.
You must login to leave a comment