Nikki
221
3
Laravel

Getting a null when accessing a relation

Posted 4 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 }}
    @php
        dd($parent->parent)
    @endphp
@endforeach

If I do this

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

I get this error

Invalid argument supplied for foreach()

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