Search code examples
laraveleloquentlaravel-bladelaravel-11

Laravel blade - show eager loaded relation values


I have two tables with a one toy many relation

  • category_type (e.g. a value of "Fruit"
  • category (e.g. a value of "Apple"

I would like to build a dropdown with values like "Fruit - Apple".

In my controller I query both tables and send it to the view.

    public function edit(Pdlocation $pdlocation)
    {
        $categories = Category::with('CategoryType:name,id')
            ->get(["name", "category_type_id","id"]);

            return view('admin.pdlocation.edit',compact('pdlocation','categories'));
    }

In my blade I try to the the name from the category (Apple) but also the name from the referenced category type (Fruit)

    @foreach ($categories as $category)
    <ul>
        <li>{{ dump($category); }}
        <li>{{ dump($category->category_type); }}
        <li>{{ $category->name }}
        <li>{{ $category->category_type->name }}
    </ul>
    @endforeach

Unfortunately I get an error of Attempt to read property "name" on null for this command $category->category_type->name.

The dump($category) gives me this output

{
  "name": "Fruit",
  "category_type_id": 3,
  "id": 2,
  "category_type": {
    "name": "Apple",
    "id": 3
  }
}

The dump($category->category_type) gives me a NULL.

How can I get the value of $category->category_type->name?


Solution

    • Make sure that the relationship method in the Category model is correctly named as "categoryType".

      public function categoryType() { return $this->belongsTo(CategoryType::class, 'category_type_id'); } enter image description here

    • with method in the query should use the relationship name as defined in the model. Like $categories = Category::with('categoryType')->get();

    • Check that the category_type_id field in the categories table correctly references the id field in the category_types table.

    If you follow above steps and make sure the relationship is properly defined and loaded, you should be able to access the name property of the CategoryType like $category->categoryType->name.