Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How does firstOrNew interact with Eloquent relationships


How does firstOrNew interact with Eloquent relationships


To use `firstOrNew()` with Eloquent relationships, you can follow these steps:

1. Define the relationship in your model, for example:

php
public function category()
{
    return $this->belongsTo(Category::class);
}

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

php
$product = Product::firstOrNew([
    'name' => 'New Product',
], [
    'category_id' => $categoryId,
]);

In this example, `'category_id' => $categoryId` is part of the relationship attributes.

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

php
if ($product->exists) {
    // Product exists
    $product->category->name; // Access the related category
} else {
    // Product does not exist
    $product->category; // Access the related (unsaved) category
    $product->save();
}

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

4. If you want to create the related model when the main model is created, you can use the `create()` method with `firstOrNew()`:

php
$product = Product::firstOrNew([
    'name' => 'New Product',
], [
    'category' => [
        'name' => 'New Category',
    ],
]);

if ($product->exists) {
    // Product exists
} else {
    // Product does not exist
    $product->save();
    // Category is automatically created and associated with the product
}

In this case, when the product is created, the related category will also be created and associated with the product.

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 models, and create or update them as needed.

Citations:
[1] https://laracasts.com/discuss/channels/eloquent/eloquent-hasone-relation-w-firstornew
[2] https://laravel.com/docs/11.x/eloquent-relationships
[3] https://laravel.com/docs/5.7/eloquent-relationships
[4] https://stackoverflow.com/questions/40911409/laravel-5-how-to-use-firstornew-with-additional-relationship-fields
[5] https://www.w3resource.com/laravel/eloquent-relationships.php