Search code examples
phplaraveleloquentlumeneloquent-relationship

How to load relationship with Eloquent?


I have a Link model and each link has an owner (represented by ownerId in DB, which is a foreign key of the User table).

Here is the Link model :

<?php namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Link extends Model {

protected $table = "Link";

// ...

// Relationships
public function owner()
{
    return $this->belongsTo(User::class, 'ownerId', 'id');
}

}

When I use $data = Link::find($linkId)->toJson(); in my LinkController, owner is included but is null in the JSON data. I also tried $data = Link::with('owner')->find($linkId)->toJson(); and $data = Link::find($linkId)->load('owner')->toJson();

And when I use $data = Link::find($linkId)->owner->toJson();, I get the user data. Is there something missing in my code?

Is there a way to load the owner in the link object and to get it via JSON without additional requests / steps ?


Solution

  • I finally found the issue. The primary key in my User table was not standard (it was a string key instead of int). I added the following lines in my User model :

    public $incrementing = false;
    public $keyType = 'string';
    

    And now $data = Link::with('owner')->find($linkId); is just working fine.