Getting a null when accessing a relation

Posted 2 months ago by Nikki

I'm not able to access the relation that I created. So in my database I have a product table and that table has a parent column and that parent column refrences the id of the product in the product table. When I dd($parent->parent) I get a null. I've been looking at this for a while and I can't see where I'm going wrong.

This is my controller code

public function productItem($slug)
    $parent_product = Product::where('slug', $slug)->with('parent')->get();

    return view('public.single_product', compact('parent_product'));

This is my model

public function parent()
        return $this->hasMany('App\Product', 'parent');

and this is what I have in my view

@foreach($parent_product as $parent)
    {{ $parent->title }}

If I do this

@foreach($parent_product as $parent)
    {{ $parent->title }}
    @foreach($parent->parent as $child)
        {{ $child->title }}

I get this error

Invalid argument supplied for foreach()

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

Reply to

Use Markdown with GitHub-flavored code blocks.