nkvolt's avatar

Eloquent relationship

I have 2 relationship as follow:

public function method()
    {
        return $this->belongsTo(Method::class, 'method_id', 'id') ;
    }
    public function transferee()
    {
        return $this->belongsTo(Transferee::class, 'transferee_id', 'id') ;
    }

However, only one relationship works (method) the other doesn't work though its table structure, model... are the same with the other (method) My mistake, I changed the foreign key of transferee() relationship to 'method_id' and it work like a charm.

Please help me to explain this situation.

Thank you so much

0 likes
3 replies
CamKem's avatar

What is the exact error you get? Can you give us the share link from the laravel debug screen?

nkvolt's avatar

The error: Attempt to read property "name" on null ({{ $item->transferee->name }})

@foreach ($data as $item)
<tr>
    <td width="10%" class="text-center">{{$item->code}}</td>
   <td width="30%">{{ $item->name }}</td>
   <td width="20%">{{ $item->method->name }}</td>
   <td width="25%">{{ $item->transferee->name }}</td>
</tr>
@endforeach

When I tried this:

$customer = Customer::with('transferee')->find(1);
dd($customer->transferee);

I got: "The relationship is undefined". I also found out that I can get the raw collection successfully with below

{{ $item->transferee }} -> {"id":9,"name":"ABCDEFEGG","created_at":"2022-08-21T17:52:12.000000Z","updated_at":"2022-08-21T17:52:12.000000Z","is_deleted":0}

But when I want to take the specified record of the collection, it failed with null

{{ $item->transferee->name }}
nkvolt's avatar
nkvolt
OP
Best Answer
Level 1

Problem was solved. The error caused by one Customer record which Tranferee_id is null.

Please or to participate in this conversation.