Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

FirstOrCreate, and Other 2-in-1 Methods

Premium
4:35

Laravel Eloquent has quite a few "two-in-one" features: do something or do something else. And I will demonstrate a few of them now.


Example 1: firstOrCreate()

What if you want to get the first record by some condition and create that record if it doesn't exist?

So, this is a typical code. You do where() and then first(). If it doesn't return anything, then you create the record.

use App\Models\User;
 
class HomeController extends Controller
{
public function index()
{
$user = User::where('email', '[email protected]')->first();
if (! $user) {
User::create([
'name' => 'Admin',
'email' => '[email protected]',
'password' => bcrypt('password'),
]);
}
 
return $user->id;
}
}

Laravel allows you to do that in one sentence without the if-statement, with firstOrCreate().

use App\Models\User;
 
class HomeController extends Controller
{
public function index()
{
$user = User::firstOrCreate(
['email' => '[email protected]'],
['name' => 'Admin', 'password' => bcrypt('password')]
);
 
return $user->id;
}
}

There are two parameters here. So first, by which condition should you specify more fields. The second parameter is other fields for creating a record.


Example 2: firstOrNew()

Similar to the first example, but here the record...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

SS
Stefan Sperling ✓ Link copied!

Your explanation of "upsert" is not very accurate. This is used to update or insert a record. If the record exists it gets updated otherwise it is inserted.