Ad

Many To Many Relationships In The Controller

- 1 answer

I want my controller to send a list of products to my view, here how I try at the moment:

Product.php

public function wishLists()
{
    return $this->belongsToMany('App\Models\WishList');
} 

Wishlist.php

public function products()
{
    return $this->hasMany('App\Models\Product');
}

WishListsController.php

public function index()
{
    $wishList = WishList::find(1);
    $products = $wishList->products()->get();
    return view('WishLists.index',compact('products'));
}

Error:

SQLSTATE[42S22]: Column not found: 1054 Champ 'products.wish_list_id' unknow in where clause (SQL: select * from `products` where `products`.`wish_list_id` = 1 and `products`.`wish_list_id` is not null)

Its seems to look for a id in the table products instead of looking in the many to many table? But I can't find why.

Ad

Answer

Product and WishList make a Many to Many relationship (at least to me). In a m---m relationship, the belongsToMany() method needs to be defined at both ends.

If this assumption is true (the relationship design) define your relations like below:

Product.php

public function wishLists()
{
    return $this->belongsToMany('App\Models\WishList');
    /**
    * if you have a pivot table with a diferent name than: 'product_wish_list'
    * use the second argument to indicate it:
    * return $this->belongsToMany('App\Models\WishList', 'custom_table_name');
    */ 
}

WishList.php

public function products()
{
    return $this->belongsToMany('App\Models\Product');
    /**
    * if you have a pivot table with a diferent name than: 'product_wish_list'
    * use the second argument to indicate it:
    * return $this->belongsToMany('App\Models\Product', 'custom_table_name');
    */ 
}

So now, in your controller:

WishListController.php

public function index()
{
    $products = WishList::find(1)->products()->get();

    return view('WishLists.index', compact('products'));
}
Ad
source: stackoverflow.com
Ad