PHP

Creating or Retrieving Models with Eloquent `firstOrCreate` and `firstOrNew`

Discover Laravel Eloquent's `firstOrCreate` to find or create a model, and `firstOrNew` to instantiate a model without saving, for flexible data management.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    protected $fillable = ['name', 'slug'];
}

class Category extends Model
{
    protected $fillable = ['name', 'description'];
}

// Using firstOrCreate:
// This method attempts to find a record using the first array of attributes.
// If no record is found, it will create one using both arrays of attributes
// and automatically save it to the database.
$tag = Tag::firstOrCreate(
    ['name' => 'Laravel'], // Attributes to find by
    ['slug' => 'laravel-framework'] // Attributes to create with if not found
);

echo "Tag ID: " . $tag->id . " (Status: " . ($tag->wasRecentlyCreated ? 'Created' : 'Retrieved') . ")
";

// Using firstOrNew:
// This method attempts to find a record using the first array of attributes.
// If no record is found, it will return a new model instance populated
// with both arrays of attributes, but it will NOT save it to the database.
// You must call $model->save() manually if you want to persist it.
$category = Category::firstOrNew(
    ['name' => 'Backend Development'], // Attributes to find by
    ['description' => 'Discussions on server-side technologies.'] // Attributes to create with if not found
);

if ($category->exists) {
    echo "Category retrieved: " . $category->name . "
";
} else {
    echo "New category instantiated: " . $category->name . " (not yet saved)
";
    $category->save(); // Manually save the new instance
    echo "Category saved with ID: " . $category->id . "
";
}
How it works: Eloquent's `firstOrCreate` and `firstOrNew` methods offer distinct ways to manage model creation and retrieval. `firstOrCreate` attempts to find a model by a given set of attributes and, if not found, creates and persists a new one using additional attributes. In contrast, `firstOrNew` also attempts to find a model but only instantiates a new model if none is found; it does not save it to the database. You must explicitly call `save()` on the `firstOrNew` result if you wish to persist the new instance, giving you more control over the saving process.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs