Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

martinszeltins's avatar

Laravel "with" returns null

Hi, I have 3 tables - users, organizations and organization_types. I'm trying to always load the organization type relationship on organization Model but it's returning null. I'm not sure why this is happening.

My controller:

public function login(Request $request)
{
    $user = User::with('organization:id,description')->first();
}

My organization model

class Organization extends Model
{
    protected $with = ['type'];
    
    public function type() {
        return $this->belongsTo(OrganizationType::class);
    }
}

In database I have users table that has "organization_id" and in organization table I have "organization_type_id".

But the result looks like this:

id: 1,
name: "Martin Zeltin",
organization: {
    id: 1,
    description: "Microsoft Inc.",
    type: null
}
0 likes
5 replies
Nakov's avatar

That is because when you say type laravel tries to match it with type_id you need to provide the full name:

public function type() {
    return $this->belongsTo(OrganizationType::class, 'organization_type_id');
}
newbie360's avatar

if follow the name convention, the method name should be

    protected $with = ['organizationType'];

    public function organizationType() {
        return $this->belongsTo(OrganizationType::class);
    }
martinszeltins's avatar

@nakov @newbie360 This still returns null

    protected $with = ['organizationType'];

    public function organizationType() {
        return $this->belongsTo(OrganizationType::class, 'organization_type_id');
    }

The query looks like this

[query] => select * from `organization_types` where 0 = 1
MichalOravec's avatar
Level 75

You have to select organization_type_id as well

$user = User::with('organization:id,description,organization_type_id')->first();

Please or to participate in this conversation.