Laravel Eloquent Relationship WithDefault Code Example

Hello Artisan

In this tutorial, I will discuss how to use withDefault with belongsTohasOnehasOneThrough, and morphOne relationship in Laravel. Sometimes you have no relationship data but you want to show default data in that case, you can use this condition.

See the below example of code to understand:

/**
 * Get the author of the post.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault();
}

 

Now you want to set a default data if no relationship data exists, then you can use:

/**
 * Get the author of the post.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault([
        'name' => 'Guest Author',
    ]);
}

 

You can also pass closer like that

public function user()
{
    return $this->belongsTo(User::class)->withDefault(function ($user, $post) {
        $user->name = 'Guest Author';
    });
}

 

Hope it can help you.

 

#laravel #laravel-8x #eloquent-relationship