Imagine following DB tables:
Clients Users
| Id | name | user_id | | ID | name |
| -- | ----- | ------ | | -- | ------ |
| 1 | NULL | 1 | | 1 | David |
| 2 | Peter | NULL |
Not each client is automatically user, but user may have client account. Users table contains only registered users, if user is client (dont have to be) the client account is created.
I have succcessfully made relations between these table is Laravel. Eloquent querying woks fine, eg.:
clients.php
public function userAcc() {
return $this->hasOne('User', 'id', 'user_id');
}
user.php
public function clientAcc() {
return $this->hasOne('Clients', 'user_id', 'id');
}
The problem is that when i query these tables:
Clients::with('userAcc')->get()
In view i have to make lots of ifs, like:
@if($client->userAcc)
{!! $client->userAcc->name !!}
@else
{!! $client->name !!}
@endif
Is there any workaround in laravel that allows me to format collections on each select query? Something like Accessor but on whole collection, so i will be able to do something like this in view:
{!! $client->realname !!}
And it writes client name from particular table.
Many thanks for any suggestions