You could try to use relation column name.
public function company()
{
return $this->belongsTo('App\Company','company_id');
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello
For some weird reason, belongsTo relation returns null for one model.
App\Product and App\User model have this
public function company()
{
return $this->belongsTo('App\Company');
}
I tried this in tinker too
>>> $u = App\User::with('company')->first();
=> App\User {#814
id: 1,
name: "Admin",
company_id: 1,
first_name: "",
last_name: "",
email: "test@admin.com",
created_at: "2015-11-13 11:41:15",
updated_at: "2015-11-13 11:41:15",
company: App\Company {#823
id: 1,
name: "Ettev├Ąte O├£",
email: "info@ettev.ee",
created_at: "2015-11-13 11:41:15",
updated_at: "2015-11-13 11:41:15",
},
}
>>> $p = App\Product::with('company')->first();
=> App\Product {#811
id: 1,
company_id: 44,
type: 1,
public: 1,
title: "Eos ea expedita voluptatem.",
name: "",
price: 856.94,
quantity: 1067.0,
unit: "",
category: 0,
scategory: 0,
sscategory: 0,
created_at: "2015-11-13 11:41:15",
updated_at: "2015-11-13 11:41:15",
company: null,
}
>>>
Both product and user model have exactly the same relation, copy-pasted. Company has hasMany relationsip for poth models. Also, when looking db at phpmyadmin, everything seems okay. I dont have company attribute mutator in product model or anyhting like that.
I use the same relation for many other models too and it has never failed. I dont know what to do.
Also, if i look at the queries (not in tinker, at product list page) then the query for companies is made:
[query] => select * from `companies` where `companies`.`id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
[bindings] => Array
(
[0] => 37
[1] => 8
[2] => 23
[3] => 15
[4] => 47
[5] => 43
[6] => 3
[7] => 17
[8] => 38
[9] => 36
[10] => 18
[11] => 27
[12] => 25
[13] => 48
[14] => 46
[15] => 9
[16] => 29
[17] => 31
[18] => 49
[19] => 13
[20] => 26
[21] => 42
[22] => 50
[23] => 24
[24] => 21
[25] => 5
[26] => 14
[27] => 44
[28] => 30
[29] => 6
[30] => 10
[31] => 19
[32] => 11
[33] => 28
[34] => 39
[35] => 7
[36] => 45
[37] => 41
[38] => 2
[39] => 22
[40] => 34
[41] => 12
[42] => 16
)
[time] => 0.53
Please or to participate in this conversation.