Advertisements

Allow null records in Laravel relationship

Advertisements

Allow null records in Laravel relationship

public function post()
{
    return $this->belongsTo(Post::class)->withDefault();
}

//default value if null relationship
public function post()
{
    return $this->belongsTo(Post::class)->withDefault([
        'comment' => 'No comments',
    ]);
}

For more code examples click here. Read laravel relationship.