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

别来无恙 提交于 2019-12-23 06:47:09

问题


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?


回答1:


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' => 'bob@example.com']);

// the below will dump out false because this entry already existed
var_dump($user->wasRecentlyCreated);

Now, lets say new@example.com doesn't exist.

$user2 = User::firstOrCreate(['email' => 'new@example.com']);

// the below will dump out true because this user was created
// in the current request lifecycle
var_dump($user2->wasRecentlyCreated);


来源:https://stackoverflow.com/questions/36543477/in-laravel-is-there-a-way-to-find-out-whether-firstorcreate-created-or-if-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!