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

aGreenCoder's avatar

Eloquent Relationship belongsTo Error

Let's assume, There Is two Table 'empData' & 'district'. 'empData' table contain 'id', 'name', 'empDistrict' ('empDistrict' contain the corresponding id of district) . and 'District' table contain 'id', 'name' of all districts.

Now I want to fetch the student's details including the district name. (Note: In the empDatatable, I contain only district id) How can I achieve this?

My Implementation My District Model

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\EmpData;
class District extends Model
{
    protected $guarded = [];
    public function empdistrict(){
        return $this->belongsTo(EmpData::class, 'empDistrict', 'id');
    }
}

My EmpData Controller

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
    $data= EmpData::all();
    return view('frontend.allusermindata',compact(['data']));
}

My Blade file where I show the data

foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict()->name}}</p>
}

But I get this error Trying to get property 'name' of non-object

0 likes
6 replies
jorgensolli's avatar

$data is a collection of EmpData, but you're calling it $user in the blade loop. Looks like you might be confused regarding what objects you're working with?

Since the error is pointing to an issue in your EmpData model, having a look at that would be helpful. Does EmpData have a relation-method called empdistrict?

tykus's avatar
tykus
Best Answer
Level 104

Your entities, attributes and relationships are not well-named. You are defining the relationship on the wrong model.

Instead, change the relationship name to district:

// EmpData
public function district()
{
    return $this->belongsTo(District::class, 'empDistrict', 'id');
}

Now:

<p>District : {{ $user->district->name ?? '' }}</p>

Aside, The reason we have the convention of foreign keys with _id suffix is to prevent this scenario where your Model's attribute empDistrict is the same as the relationship you are trying to define empdistrict.

3 likes
achatzi's avatar

@devwebtk Along with the comments that the others made, I would also like to point out that when using a relation name with parenthesis it is a builder not a property, which means that it will make a query in the database.

So this

$user->empdistrict()->name

should be

$user->empdistrict->name

Please or to participate in this conversation.