jeudi 17 octobre 2019

Displaying favourites product laravel

I'm trying to make this functionality work, so when a user clicks the add to favorite button it should add the product to his favourites products and also if the product is already added to favorite the button(add to favorite) should disappear , So far when I click the add to favorite button it adds the product to database but the button doesn't disappear and also if I click the favorites page to see all his favorites products , I don't see any product(empty). How can I make the button disappear when the product is already added to favourites and also how to make the favourites page display all the products of that user?

Controller

public function store(Request $request, $product)
{
    if(\Auth::check()){
        $request->user()->favouriteProducts()->syncWithoutDetaching($product);
        return redirect()->back();
    } else {

    }
}

public function favouriteslist(Request $request)
{
    $products = $request->user()->favouriteProducts()->paginate(5);
    //dd($products);
    return view('front.wishlist', compact('products'));
}

Blade

@if(\Auth::check())
    @if(!$product->favouritedBy(Auth::user()))
        <span class="pull-right">
            <a href="" onclick="event.preventDefault(); document.getElementById('product-fav-form').submit();">Add to Favourites</a>
            <form id="product-fav-form" class="hidden" action="" method="POST">
                
            </form>
        </span>
    @endif
@endif

User model

public function favouriteProducts(){
    return $this->morphedByMany(Product::class,'favouriteable')
        ->withPivot(['created_at'])->orderBy('pivot_created_at', 'desc');
}

Product Model

public function favourites(){
    return $this->morphToMany(User::class, 'favouriteable');
}

public function favouritedBy(User $user){
    return $this->favourites->contains($user);
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2VNaXHI
via IFTTT

Aucun commentaire:

Enregistrer un commentaire