Courses

Laravel 12 Eloquent: Expert Level

WasCreated, IsDirty and Other Checks If Model Was Changed

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Using wasRecentlyCreated() to check model status
- Implementing isDirty() for tracking changes
- Understanding wasChanged() for saved changes
- Comparing pre and post-save state detection

Link to the repository

[Only for premium members]

There are a few helpful Eloquent functions that help you to know whether the Eloquent object was changed recently or during the request of Laravel.


Example 1: wasRecentlyCreated()

So there is firstOrCreate(), which tries to find the first record by email or creates that with name and password.

use App\Models\User;
 
class HomeController extends Controller
{
public function index()
{
$user = User::firstOrCreate(
['email' => 'admin@admin.com'],
['name' => 'Admin', 'password' => bcrypt('password')]
);
 
dump($user->wasRecentlyCreated ? 'Created' : 'Found');
}
}

And there's wasRecentlyCreated. This is a property, not a function.

And if you launch that code on an empty database the first time, it will say created because it created the object, but if you relaunch it the second time, it will say found because it didn't create the object during that second request.


Example 2: isDirty()

The second helpful method is isDirty(). If you change any Eloquent method property during...

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

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