Get information from a foreign key, when it has multiple entries in a table

Published 2 years ago by snapper

I am using Laravel 4.2 and have a table called users and a column in that table labeled name. I also have a transactions table that has 2 columns which are both foreign keys that reference the primary key of the users table. One of the rows in the transactions is labeled given_to and the other is labeled received_from. How can I access the name associated with the given_to user id from the transactions table using Eloquent? I tried the following in a view and received a trying to get property of non-object error:

@foreach($transactions as $transaction) {{ $transaction->given_to->name }} @endforeach

phildawson

@snapper

users
id name

transactions 
id given_to received_from

You have to let it know the relationship. In this case they belong to, and you need to specify the column it will be making the join on otherwise it'll be looking for a given_to_id column by default.

class Transaction extends Model
{
    function given_to()
    {
        return $this->belongsTo(User::class, 'given_to');
    }

    function received_from()
    {
        return $this->belongsTo(User::class, 'received_from');
    }
}

then you can use it like you had

foreach($transactions as $transaction) {
    $transaction->given_to->name;
}
snapper

I tried the following based off of your proposed solution and received a "trying to get property of non object" error:

Inside of the Transaction Model: class Transaction extends Eloquent { public function given_to() { return $this->belongsTo('User', 'given_to'); } }

foreach($transactions as $transaction) { $transaction->given_to->name; }

bobbybouwmann

It's not weird that you get a property not found. What if one of the transactions in your foreach doesn't have a related given_to? Then given_to would return null and ->name on null doesn't work.

In this case you can do a check

foreach($transactions as $transaction) {
    if (count($transaction->given_to)) {
        dd($transaction->given_to->name);
    }
}
snapper

foreach($transactions as $transaction) { $transaction->given_to->name; }

would return null because it's going to return the key in the transactions table that's labeled given_to, but if we define the model relationship using camelcase, then we could then use this:

foreach($transactions as $transaction) { $transaction->givenTo; }

to access the model object and this:

foreach($transactions as $transaction) { $transaction->givenTo->name; }

to pull the name associated with each model object

bobbybouwmann

Yes you are correct. I didn't know your model had a field of given_to as well!

Do you have any other questions?

snapper

Nope, not for this query. Thanks for the information and insight.

Please sign in or create an account to participate in this conversation.