I'm creating a functionality where user can add the product with multiple images to favorites, the problem happens when user clicks to see the product details before adding to favorites it throws an error Call to undefined method App\ProductsPhoto::favouritedBy(). In blade the line that cause problem is this
@foreach($product->ProductsPhoto as $product)
<img src="">
@endforeach
if I remove that line it displays no error but also not displaying the images(carousel) and if I change the the line to
@if(count($product->ProductsPhoto))
<img src="">
@else
@endif
it displays only the first image . And if I add these functions
public function favourites(){
return $this->morphToMany(User::class, 'favouriteable');
}
public function favouritedBy(User $user){
return $this->favourites->contains($user);
}
to the ProductsPhoto model and click the product details it shows all the images but if I click the add to favorite button it says 404 means that route doesn't exist while it does. How can I display all the images and make it work?
Controller
public function store(Request $request, Product $product)
{
$request->user()->favouriteProducts()->syncWithoutDetaching([$product->id]);
return back();
}
ProductDetail Blade
@foreach($products as $product)
<h2>USD </h2>
@foreach($product->ProductsPhoto as $product)
<img src=">
@endforeach
@endforeach
@if(!$product->favouritedBy(Auth::user()))
<a href="" onclick="event.preventDefault(); document.getElementById('product-fav-form').submit();">Add to Favorite </a>
<form id="product-fav-form" class="hidden" action="" method="POST">
</form>
@endif
Route
Route::post('/products/{product}/favourites', 'HomeController@store')
->name('product.fav.store');
Product Model
public function ProductsPhoto()
{
return $this->hasMany('App\ProductsPhoto','product_id');
}
public function favourites(){
return $this->morphToMany(User::class, 'favouriteable');
}
public function favouritedBy(User $user){
return $this->favourites->contains($user);
}
ProductsPhoto Model
class ProductsPhoto extends Model
{
protected $fillable = ['product_id', 'filename'];
public function product()
{
return $this->belongsTo('App\Product','product_id');
}
}
User model
public function favouriteProducts(){
return $this->morphedByMany(Product::class,'favouriteable')
->withPivot(['created_at'])->orderBy('pivot_created_at', 'desc');
}
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/33EzvoT
via IFTTT
Aucun commentaire:
Enregistrer un commentaire