Laravel firstOrNew如何检查它是第一个还是新的?

我'm using Laravel'的功能 firstOrNew() 来创建新用户或查找并更新现有用户 .

在创建对象之后,如果它之前存在或者它是新对象,我怎么知道?

这个想法是这样的:

$user = \App\User::firstOrNew([
    'email' => $userData->getEmail(),
    'name' => $userData->getName(),
]);

if ($user->new) { // some way to check
    // user was created now
} else {
    //user already existed
}

回答(3)

3 years ago

您可以检查模型上的 exists 属性 .

if ($user->exists) {
    // user already exists
} else {
    // user created from 'new'; does not exist in database.
}

3 years ago

您可以检查您的用户是否最近创建过 .

if ($user->wasRecentlyCreated) {
    // new user
} else {
    // user already exists
}

(来源:Thomas Kim来自this answer

3 years ago

您始终可以在模型中检查ID(或任何其他唯一主键) .

$user = \App\User::firstOrNew([
    'email' => $userData->getEmail(),
    'name' => $userData->getName(),
]);

if($user->id) {
    // The user exists and was retrieved from the database...
}

if (!$user->id) {
    // The user was not found in the database and a new User model was created...
}

重要的是要记住,在使用 $user->save() 持久化模型后,您将无法使用 $user->id 来检查它是否在数据库中找到 . 这是因为Eloquent在保存后会填充新模型的所有属性 .