Search code examples
laraveleloquent-relationship

Laravel 8.83.27, Undefined property: stdClass::$image (view: /Application/../..)


I have two tables:

  • items
    • id
    • name
    • description
    • created_at
    • update_at
  • images
    • id
    • name
    • item_id
    • created_at
    • updated_at

I did build a one-to-one relationship between the Item model and Image model.

Item model

<?php 

namespace App/Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\Image;

class Item extends Model
{
    use HashFactory;

    public function image()
    {
        return $this->hasOne(Image::class, "item_id");
    }
}

Image model

<?php

namespace App/Models;

use App\Models\Item;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Item extends Model
{
    use HashFactory;

    public function item()
    {
        return $this->belongsTo(Item::class);
    }
}

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Reuquest;
use Illuminate\Support\Facades\DB;

class RootController extends Controller
{
    $items = DB::table("items")->get();

    return view("index", ["items" => $items]);
}

In The view I wanted to show the image name of each item, therefore I proceeded the following way,

<div>
   @foreach($items as item)
       <span>{{ $item->image->name }}</span>
   @endforeach
</div>

I, despite my checkings and analyses, couldn't figure out where I was wrong in this code.


Solution

  • $items = DB::table("items")->get();
    

    should be:

    $items = Item::all();
    

    Using the DB facade instead of the Eloquent model means none of your model's functionality or settings apply to the resulting query.