PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] Blank object in Eloquent belongsTo()

 January 19, 2022     eloquent, laravel, laravel-blade     No comments   

Issue

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!


Solution

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.



Answered By - zahid hasan emon
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing