Sandeep
Sandeep

Reputation: 1053

hasOne Relation not working in laravel

Hi I want to make relationship between two tables first Table is product and second is productimages

ProductController.php

public function product(){
     $products = Product::all();
     dd($products->images);
}

Product.php (modal)

class Product extends Model
{
      public $timestamps = false;
      //

      public function images()
      {
         return $this->hasOne(ProductImage::class);
      }
 }

ProductImage.php(model)

class ProductImage extends Model
{
    public function product(){
       return $this->belongsTo(Product::class);
    }
}

When i am using this method $products = Product::find(1); working find but i need all.

Thanks

Upvotes: 1

Views: 1045

Answers (2)

Md Adil
Md Adil

Reputation: 307

Product::with('images')->get();

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

When you're doing $products->images you're trying to access property of collection.

Preload all products with their images, use with() method:

$products = Product::with('images')->get();

Then you'll be able to get image of each product and avoid N + 1 problem:

@foreach ($products as $product)
    // Access $product->image here
@endforeach 

Upvotes: 1

Related Questions