Courses

Laravel 12 Eloquent: Expert Level

FirstOrCreate, and Other 2-in-1 Methods

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Understanding firstOrCreate() method usage
- Implementing firstOrNew() for unsaved instances
- Using updateOrCreate() for conditional updates
- Working with upsert() for bulk operations

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', 'admin@admin.com')->first();
if (! $user) {
User::create([
'name' => 'Admin',
'email' => 'admin@admin.com',
'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' => 'admin@admin.com'],
['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 28 lessons of this course? (71 min read)

You also get:

  • 75 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord