laravel one to many relationships returning null

Posted 3 months ago by Mubeenali

here are two models.product and image In My product model:

product.php

 // one to many   relationship with images table 
public function images()
{
    return $this->hasMany('App\image');
}

image.php

 public function product()
{
    return $this->belongsTo('App\product');


}

ProductController

public function productDetail($slug)
{
    $product = product::where([
      ['slug',$slug],
      ['seller_id' ,Auth::id()],
    ])->first();
    
  if($product)
    {
      

      //give images from the image table 
      $product_image   = \App\product::find(11)->images;
         $arr = array();

          foreach(\App\product::find($product->id)->images() as $i)
          {
            array($arr,$i->image);
          }

          dd($arr);  // problem returning always null 
        return view('backEnd.seller.product_detail',compact('product','image')); 
    }

Problem Statement: In my controller when i tried to get all the images of specific product i am getting Null . I am trying to solve this for one day ago.please help me Which i am missing?

Product Migration :

 public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('seller_id');
        $table->unsignedInteger('category_id');
        $table->string('product');
        $table->text('discription');
        $table->timestamps();
    });
}

Image Migration :

  public function up()
{
    Schema::create('images', function (Blueprint $table){
        $table->increments('id');
        $table->unsignedInteger('product_id');
        $table->string('image');
        $table->timestamps();
    });
}

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.