Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mefsh's avatar
Level 2

withDefault on related Model

Hello, i have 3 database tables, which structure looks like this

user: id, name, email, ...,

rank: id, name,

users_ranks: id, user_id ->unique, rank_id,

And my code for models looks like this: User:

public function rank()
{
    return $this->hasManyThrough('App\Rank', 'App\UserRank', 'user_id', 'id', 'id', 'rank_id');
}

UserRank:

public function rank()
{
    return $this->belongsTo('App\Rank', 'rank_id', 'id');
}

public function user()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}

Rank:

public function userRank()
{
    return $this->hasMany('App\UserRank', 'rank_id', 'id');
}

public function user()
{
    return $this->belongsToMany('App\User', 'user_id', 'id');
}

On Another model with belongsTo i was able to use withDefault on it. What about hasManyThrough, when i want to return some default values if the rank is null while fetching Users like this

User::with('Rank')->get();

0 likes
5 replies
mefsh's avatar
Level 2

I want to get the User Collection with Rank inside, but with default values on Rank when it's null. I know how to fetch related data. The problem is that i want to do something like this:

public function rank()
{
    return $this->hasManyThrough('App\Rank', 'App\UserRank', 'user_id', 'id', 'id', 'rank_id')->withDefault(['name' => trans('rank.no_rank')]);
}

but hasManyThrought has no withDefault method.

Vilfago's avatar

If you set a default value in your database, the default value will be injected instead of null when you create a new line.

rin4ik's avatar

u can use optional helper . like :

{{optional($user->rank)->title}}

if your rank null you don't get an error like Trying to get property of non object

mefsh's avatar
Level 2

@Vilfago Not exacly, when i want to use multilanguage i prefer to keep null field on Database, and then return localization related data.

@rin4ik The response will be returned as json to ajax request. I would like to return localization related "no data" information, it's because i don't want my js code that looks like this (and it has to be called inside blade file...)

response.forEach(user => {
[...]
    tdRank.appendChild(document.createTextNode(user.rank !== undefined ? user.rank['name'] : "{{__('user.no_rank')}}"));
[...]
});
mefsh's avatar
Level 2

Refresh

Maybe someone have a good way how to handle with lang(localization) and routes files in js, instead of trying to do something like withDefault on hasManyThrough?

Please or to participate in this conversation.