HPM HPM - 18 days ago 5
PHP Question

Eloquent: access model relation or create new

Suppose there are 2 table in database: user, appUser (user has one appUser and relation are defined) Having user id, in order to update appUser data we can use the following code (if there is no appUser relative model):

$user = user::find($userID);
if(count($user->appUser) == 0){
$appUser = new appUser();
$appUser->column = $value;
$user->appUser->save();
} else {
$appUser = $user->appUser;
$appUser->column = $value;
}
$user->appUser()->save($appUser);


Looks fine, but what if I there is another contact table (appUser has one contact), so for updating contacts we should add more ifs and elses to make sure appUser and contact relations exist. My question is that is there any concise way to load a relation and create new if does not exists in laravel eloquent?

In that case it would be like:

$user = user::find($userID);
// No Exception!
$user->appUser->column = $value;
$user->appUser->save();

Answer

As of Laravel 5.3.23, there is a new withDefault method added to HasOne relationships that should help with this.

In your example, your user model would have the following relationship:

public function appUser() {
    return $this->hasOne(appUser::class)->withDefault();
}

What this will do is, if there is no related record in the database, it will return a new instance of the related (appUser) class. So, your code would end up looking like:

$user = user::find($userID);
// if user has an appuser, $user->appUser will return it;
// otherwise, it will return a new instance of your appUser model
$user->appUser->column = $value;
$user->appUser()->save();