I'm trying to define a Many to Many relationships using "belongsToMany" relationship between 2 tables with a lookup table.
These are my tables:
I have a category_product like this
ProductController.php
public function index()
{
$categories = Category::with('products')->where('parent_id', 0)->get();
return view('Home.lists.product', compact('categories'));
}
Category..php
public function products()
{
return $this->belongsToMany(Product::class);
}
product.blade.php
#foreach($categories as $category)
#foreach($category->products as $product)
#dd($product->id)
#endforeach
#endforeach
I see this. 3 // resources\views/Home/lists/portfolio.blade.php
I want to return 3,5,4.
It is returned only 3. and I want to return all products.
Related
I'm trying write an website with Laravel (current version is 5.7) and I have 3 models as: Post, User and Fav. I'm using a simple form to add posts to "favs" table which has 3 columns as; id, user_id and post_id. And I want to list posts that user added favorites bu I can't use "hasMany" method properly.
I can use variables like; $post->user->name but I can't figure it out how to use relationship with "favs" table.
Post Model
public function user() {
return $this->belongsTo('App\User');
}
public function favs() {
return $this->hasMany('App\Fav');
}
Fav Model
public function users() {
return $this->hasMany('App\User');
}
public function posts() {
return $this->hasMany('App\Post', 'post_id', 'id');
}
User Model
public function posts() {
return $this->hasMany('App\Post');
}
public function favs() {
return $this->hasMany('App\Fav');
}
Controller
public function user($id){
$favs = Fav::orderBy('post_id', 'desc')->get();
$user = User::find($id);
$posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
}
The Fav model only has one User and Post each, so you need to use belongsTo() instead of hasMany and change the method names to singular. You can also remove the additional parameters in post() since they're the default values.
public function user() {
return $this->belongsTo('App\User');
}
public function post() {
return $this->belongsTo('App\Post');
}
Loading all Posts that a user has favorited:
$user->favs()->with('post')->get();
The with() method is used to eager load the relationship.
Now you can loop through the Favs:
#foreach($favs as $fav)
{{ $fav->post->name }}
#endforeach
I think you can change these two lines of your code to
$posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
to
$posts = Post::where('user_id', $id)->where('status', '4')->latest()->paginate(10);
return view('front.user', compact('user', 'posts', 'favs'));
And for retrieving favorite posts of an user,
if you will change the fav table to make it a pivot table only to handle a many to many relationships between Post and User, you can get it as $user->posts, for a separate model, I think you can consider something like $user->favs and in view
In Fav model
public function user() {
return $this->belongsTo('App\User');
}
public function post() {
return $this->belongsTo('App\Post');
}
and in view
#foreach ( $user->favs as $fav )
{{ $fav->post->id }}
#endforeach
If an User, per example, have many Favs you need to use a Iteration Block, like foreach.
Example:
foreach($user->favs as $fav) {
dd($fav) // do something
}
Ps.: Be careful not to confuse hasMany and belongsToMany.
Image model:
public function getImage(){
return $this->belongsTo('App\Product');
}
Product model:
public function product(){
return $this->hasMany('App\Image');
}
Controller:
public function index()
{
$products = Product::all(); //Select *
return view('product.index',compact('products'));
}
View:
#foreach($products as $product)
<td>{{ $product->getImage->image_link}}</td>
#endforeach
Error:
Trying to get property 'image_link' of non-object (View:
C:\xampp\htdocs\ecommerce\resources\views\product\index.blade.php)
Their should be a relation between post and product with product id
In Product.php
public function product(){
return $this->hasMany('App\Image');
}
then you can use $product->images->image_link
Is there a product_id field in your image table? and is there hasMany in your Product model?
In your Product model should be a relation like as below.
Product.php
public function images(){
return $this->hasMany('App\Image');
}
After then, you can use images in product for loop $product->images->image_link.
I have category and subcategory table with many to many relationship
class Category extends Model {
protected $table='categories';
protected $fillable=['name'];
public function subcategories() {
return $this->belongsToMany('App\Modules\Subcategory\Models\Subcategory', 'categories_subcategories', 'category_id', 'subcategory_id');
}
}
Subcategory
class Subcategory extends Model {
protected $table='subcategories';
protected $fillable=['name'];
public function categories()
{
return $this->belongsToMany('App\Modules\Category\Models\Category', 'categories_subcategories', 'subcategory_id', 'category_id');
}
}
in controller
public function catSubList()
{
$subcategories = Subcategory::with('categories')->get();
return view('Subcategory::category_subcategory',compact('subcategories'));
}
But in view when i tried to access the data with following view
#foreach($subcategories as $row)
<td>{{$i}}</td>
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
#endforeach
I got the error like :
ErrorException in Collection.php line 1527: Property [name] does not exist on this collection instance.
How do i access $row->categories->name ? anyone with the suggestion please?
You have to make another foreach() loop Because your subcategories belongsToMany categories. row->categories returns a collection, not an object. Thus the error.
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
#foreach($row->categories as $category)
<td>{{$category->name}}</td>
#endforeach
Update
Getting a category with all subcategories. Simply invert your query
$category = Category::with('subcategories')
->where('name', '=', 'cars')
->first();
//will return you the category 'cars' with all sub categories of 'cars'.
Without eager loading
$category = Category::find(1);
$subacategories = $category->subcategories;
return view('Subcategory::category_subcategory', compact('category', subcategories));
I asked question whose link is:
Link
Now my problem is that I want to show "CategoryName' of in food details.For that I add function in Categories.php model as:
public function food()
{
return $this->hasMany('App\Food','food_categories','Category_id','Food_id');
}
and in food.php
public function restaurant()
{
return $this->belongsToMany('App\Restaurant','food_restaurant','Food_id','Res_id');
}
public function categories()
{
return $this->belongsTo('App\Categories','food_categories');
}
Then in show.blade.php I add:
#foreach ($food->restaurant as $restaurant)
<h3><p>RestaurantName:</h3><h4>{{$restaurant->ResName}}</p></h4>
<h3><p>Contact #:</h3><h4>{{$restaurant->Contact}}</p></h4>
<h3><p>Location:</h3><h4>{{$restaurant->Address_Loc}}</p></h4>
#endforeach
#foreach ($food->categories as $categories)
<h3><p>CategoryName:</h3><h4>{{$categories->CategoryName}}</p></h4>
#endforeach
And I changed controller to :
public function show($Food_id)
{
$food = Food::with('restaurant.categories')->findOrFail($Food_id);
return view('show', compact('food'));
}
But it does not shows me categoryname.Plz help me where is the problem?
With Eager loading, "dot" notation loads nested relations.
In your controller you do
Food::with('restaurant.categories')
..this queries the restaurant() relation on the Food model, and that Restaurant's categories() relation.
I think you might need to call
Food::with('restaurant', 'categories')
as this will query both relations on the Food model.
I have two main tables with relationships many to many and a pivot table.
Tables
Model Product
public function orders()
{
return $this->belongsToMany('App\Order');
}
Model Order
public function products()
{
return $this->belongsToMany('App\Product', 'OrderDetails');
}
And
$orders = Equipment::all();
#foreach($orders as $order)
#foreach($order->products as $product)
{!! $product->name !!} //it works
// How to print the value of the quantity?
#endforeach
#endforeach
What should I do to print the value of the quantity?
Try ->pivot->quantity:
{!! $product->pivot->quantity !!}
Also, add withPivot to a ralationship:
return $this->belongsToMany('App\Product', 'OrderDetails')->withPivot('quantity');
https://laravel.com/docs/5.2/eloquent-relationships#many-to-many