Home > Software design >  Blank object in Eloquent belongsTo()
Blank object in Eloquent belongsTo()

Time:12-01

I'm trying to display which one attribute (code) of Item. ServiceItem has Item as a foreign key. But I can't get the Item at all.

This one gives a blank object in blade template:

@foreach ($service->serviceItems as $serviceItem )
    {{ json_encode($serviceItem->item()) }}
@endforeach

enter image description here

Here's my model declaration:

//ServiceItem model
class ServiceItem extends Model
{
    use HasFactory;
    public $fillable = ['service_id', 'item_id', 'values'];

    public function service()
    {
        return $this->belongsTo(Service::class, 'foreign_key');
    }

    // this doesn't work
    public function item()
    {
        return $this->belongsTo(Item::class, 'foreign_key');
    }
}

// Service model
class Service extends Model
{
    use HasFactory;
    public $fillable = ['user_id', 'site_id', 'title', 'status', 'remarks', 'report', 'date'];

    public function user()
    {
        return $this->belongsTo('\App\Models\User');
    }

    public function site()
    {
        return $this->belongsTo('\App\Models\Site');
    }

    public function serviceItems() {
        return $this->hasMany('\App\Models\ServiceItem');
    }

}

This is my controller:

public function index()
{
    $services = Service::latest()->paginate(5);
    return view('services.index', compact('services'))
        ->with('i', (request()->input('page', 1) - 1) * 5);
}

Please help me to display the code attribute in Item from Service!!! Thanks a lot!

CodePudding user response:

I suppose you read the Laravel doc of model relationship definition. They referenced to put foreign key as the second parameter, not the foreign_key as word but your actual foreign key that reference the parent table. you have to change the model code.

class ServiceItem extends Model
{
    use HasFactory;
    public $fillable = ['service_id', 'item_id', 'values'];

    public function service()
    {
        return $this->belongsTo(Service::class, 'service_id');
    }

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

and then $serviceItem->item should work as expected.

  • Related