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

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

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 38 video+text lessons of this course? (1 h 34 min)

You also get:

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