Single Models

Retrieving Single Models and Aggregates

find() looks up a key and first() or firstWhere() the first match, returning null on a miss. findOrFail() throws ModelNotFoundException instead ("No query results for model [App\Models\Product] 99"), which a controller turns into the 404 of Route Model Binding, and sole() demands exactly one row:

Single models, aggregates, and firstOrCreateSQL
use App\Models\Product;
echo json_encode([Product::find(99), Product::count(), Product::max('price')]), "\n";
$p = Product::firstOrCreate(['sku' => 'BK-GIT-01'], ['title' => 'Git Under Pressure',
    'category_id' => 2, 'price' => 27.5]);
echo $p->id, ' ', $p->wasRecentlyCreated ? 'created' : 'found', "\n";
Output
...
[null,8,"49.00"]
...
-- insert into `products` (`sku`, `title`, `category_id`, `price`) values ('BK-GIT-01', 'Git
Under Pressure', 2, 27.5)
9 created

max() returned the string "49.00", since PDO delivers DECIMAL as a string. firstOrCreate() selects by its first array and inserts both merged; firstOrNew() returns an unsaved model instead. When two requests both miss, Laravel 13 2,157 inserts through createOrFirst(), which catches the unique-key violation and selects the winner's row, so the lookup columns need a unique index, as sku has.