It looks like you're not defining your relationship correctly. Your isOnline
method creates a HasMany
relation but runs the select
method and then the latest
method on it, which will end up returning a Builder
object.
The correct approach is to only return the HasMany
object from your method and it will be treated as a relation.
public function accounts()
{
return $this->hasMany('App\Accounting', 'userid');
}
Then if you want an isOnline
helper method in your App\User
class you can add one like this:
public function isOnline()
{
// This gives you a collection of \App\Accounting objects
$usersAccounts = $this->accounts;
// Do something with the user's accounts, e.g. grab the last "account"
$lastAccount = $usersAccounts->last();
if ($lastAccount) {
// If we found an account, return the rtype column
return $lastAccount->rtype;
}
// Return something else
return false;
}
Then in your controller you can eager load the relationship:
$users = User::with('accounts')->get(['field_one', 'field_two]);
Then you can do whatever you want with each App\User
object, such as calling the isOnline
method.
Edit
After some further digging, it seems to be the select
on your relationship that is causing the problem. I did a similar thing in one of my own projects and found that no results were returned for my relation. Adding latest
seemed to work alright though.
So you should remove the select
part at very least in your relation definition. When you only want to retrieve certain fields when eager loading your relation you should be able to specify them when using with
like this:
// Should bring back Accounting instances ONLY with rtype field present
User::with('accounts:rtype');
This is the case for Laravel 5.5 at least, I am not sure about previous versions. See here for more information, under the heading labelled Eager Loading Specific Columns