Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Laravel, is there a way to find out whether `firstOrCreate` created or if it found the row?

In Laravel, is there a way to differentiate between firstOrCreate creating the row and if finding out the row exists from before?

Or will I have to manually do a get() first, and then create the row?

like image 682
Pat Avatar asked Apr 11 '16 08:04

Pat


People also ask

How do I know if my data is saved in laravel?

Check if model got saved$myModel->save()) { App::abort(500, 'Error'); } //User got saved show OK message return Response::json(array('success' => true, 'user_added' => 1), 200);

What does get () do in laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.


1 Answers

If you created the model in the current lifecycle, then the model's wasRecentlyCreated attribute will be set to true. Otherwise, that attribute will be set to false.

In other words, lets say you have a user with the email, bob@example.

$user = User::firstOrCreate(['email' => '[email protected]']);  // the below will dump out false because this entry already existed var_dump($user->wasRecentlyCreated); 

Now, lets say [email protected] doesn't exist.

$user2 = User::firstOrCreate(['email' => '[email protected]']);  // the below will dump out true because this user was created // in the current request lifecycle var_dump($user2->wasRecentlyCreated); 
like image 146
Thomas Kim Avatar answered Sep 21 '22 09:09

Thomas Kim