Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can firstOrNew be used with hasOne relationships
    Laravel Eloquent firstOrNew hasOne relationship PHP model relationships


Can firstOrNew be used with hasOne relationships


Yes, you can use `firstOrNew()` with Eloquent's `hasOne` relationships. Here's how it works:

1. Define the `hasOne` relationship in your model:

php
public function phone()
{
    return $this->hasOne(Phone::class);
}

2. When using `firstOrNew()`, pass the relationship attributes along with the model attributes:

php
$user = User::firstOrNew([
    'name' => 'John Doe',
], [
    'phone' => [
        'number' => '555-1234',
    ],
]);

In this example, `'phone' => ['number' => '555-1234']` are the relationship attributes.

3. After calling `firstOrNew()`, you can interact with the relationship:

php
if ($user->exists) {
    // User exists
    $user->phone->number; // Access the related phone
} else {
    // User does not exist
    $user->phone; // Access the unsaved related phone
    $user->save();
    // Phone is automatically created and associated with the user
}

When the user is new (not existing in the database), `$user->phone` will return the unsaved related phone instance. You can then save the user and its related phone together.

By passing the relationship attributes along with the model attributes to `firstOrNew()`, you can efficiently check for the existence of a model and its related model, and create or update them as needed[1][3].

Citations:
[1] https://laracasts.com/discuss/channels/eloquent/eloquent-hasone-relation-w-firstornew
[2] https://stackoverflow.com/questions/40911409/laravel-5-how-to-use-firstornew-with-additional-relationship-fields
[3] https://laravel.com/docs/11.x/eloquent-relationships
[4] https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Relations/HasOne.html
[5] https://laravel-news.com/firstornew-firstorcreate-firstor-updateorcreate