Camron Cade

Artisan web development, mostly using Laravel.

Laravel Eloquent's ->firstOr() method

I stumbled on another hidden gem today.

I've know that Laravel has both ->firstOrNew() and firstOrCreate() queries.

But for more complicated scenarios, you can run firstOr() which accepts a callback as the first argument that is run if the query does not turn up any results.

This is really useful if you want to make sure you always have a model returned, but maybe need to do something a tad different on the model's creation.

The API documentation talks this here

Note: this only works on Laravel 5.4 and above.