skip to Main Content

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 IlluminateDatabaseEloquentFactoriesHasFactory;
use AppModelsImage;

class Item extends Model
{
    use HashFactory;

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

Image model

<?php

namespace App/Models;

use AppModelsItem;
use IlluminateDatabaseEloquentFactoriesHasFactory;

class Item extends Model
{
    use HashFactory;

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

Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpReuquest;
use IlluminateSupportFacadesDB;

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.

2

Answers


  1. Chosen as BEST ANSWER

    Thank you very much, everything worked out when changed the query builder DB to the Item:all().


  2. $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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search