Skip to main content

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

Read more here

WasCreated, IsDirty and Other Checks If Model Was Changed

Premium
2:51

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' => '[email protected]'],
['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 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

No comments yet…