Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

I'm having trouble using $appends when retrieving a relationship using eager $with. Now this is just a simple example I put together.

User.php

class User extends Eloquent { 
   protected $with = array('account');
   public function account() { return $this->hasOne('Account'); }
}

Account.php

class Account extends Eloquent {
   protected $hidden = array('pin');
   public function user() { return $this->hasOne('User'); }

   public function getPinAttribute()	{
      return $this->attributes['pin']; // or a computed value
   }
}

Now using the ->setAppends() I should be able selectively include it in the results of ->toArray(). For instance:

$account = Account::find(1);
$account->setAppends(array('pin'));
$account->toJSON(); 
/* results includes the pin */

However, this doesn't seem to work through a relationship / eager loading.

$user = User::find(1);
$user->setAppends(array('pin')); 
/* or $user->account->setAppends(array('pin')); */
$user->toJSON(); 
/* results does not include pin, append doesn't effect result. */

Is there a way to set an $appends through an eager load or relationship?

Sources: http://laravel.com/docs/eloquent#converting-to-arrays-or-json

Last updated 2 years ago.
0

What result do you expect exactly?

Last updated 2 years ago.
0

I would expect the responding array to contain the Appends attribute. In this case the pin.

For instance the the setAppends works as follows:

$account = Account::find(1);
$account->setAppends(array('pin'));
$account->toJSON(); 

And it's result something like (includes pin because of setAppends):

{
    "name": "Account1",
    "type": "blue",
    "pin": 1234
}

Now the append through a relationship (or eager load) ideally would be able to also use setAppends:

$user = User::find(1);
$user->setAppends(array('pin')); 
/* or $user->account->setAppends(array('pin')); */
$user->toJSON();

And it's expected result something like:

{
    "first_name": "Bob",
    "last_name": "Hope",
    "account": {
        "name": "Account1",
        "type": "blue",
        "pin": 1234
    }
}

However the 'pin' doesn't get included as expected as hoped.

Last updated 2 years ago.
0

At the time of this writing the only way of doing what you want is manually.

$account = Account::find(1);
$account->pin = $account->pin;
$account->toJSON();

Since then I made a commit to the framework adding the append() method.

Now you use it like this:

$account = Account::find(1)->append('pin')->toJSON();
0

Sign in to participate in this thread!

Eventy

Your banner here too?

TheBox193 thebox193 Joined 16 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.