0

I have a relationship between Product and Photo Models.

Product Model :

use Illuminate\Database\Eloquent\Model;
use App\Product;
use App\Photo;

class Product extends Model
{
    public function photos() {
        return $this->hasMany(Photo::class, 'product_id');
    }
}

Photo Model :

use Illuminate\Database\Eloquent\Model;
use App\Photo;
use App\Product;

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

When i get products like :

$product = Product::find($id)->with('photos')->first();

dd($product);

Output :

{
    "id":1,
    "title":"some product",
    "photos":[
        {
            "id":1,
            "path":"a photo 1 path"
        },
        {
            "id":2,
            "path":"a photo 2 path"
        },
        {
            "id":3,
            "path":"a photo 3 path"
        }
    ]
}

The issue when i try to access $product->photos i get nothing. just like an empty key.

If i try to dd($product->photos) i get null

The array key exists and containing data, why when accessing it, it returns nothing?

1 Answer 1

1

I figured out the problem. it's a conflict

I was having column called photos in products table and it's same as the relationship name :

public function photos() { // this photos name
    return $this->hasMany(Photo::class, 'product_id');
}

so when i was trying to access photos it was calling the column photos not the relashionship name, and the column was empty and that's the cause it was always returning nothing.

Thanks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.