我使用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
}
答案 0 :(得分:65)
您可以查看模型上的exists
属性。
if ($user->exists) {
// user already exists
} else {
// user created from 'new'; does not exist in database.
}
答案 1 :(得分:8)
您可以检查您的用户是否最近创建过。
function getUserLocation() {
function locationSuccess(position) {
console.log("success");
var coords = position.coords;
generateURL(coords);
}
function locationError() {
console.log("error")
}
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
function generateURL(coords) {
var URL = 'http://example.com/?lat=' + coords.latitude + '&long=' + coords.longitude;
console.log(URL);
}
function app() {
getUserLocation();
}
window.onload = app();
(来自:Thomas Kim的this answer)
答案 2 :(得分:1)
您始终可以在模型中检查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在保存新模型后会填充新模型的所有属性。
答案 3 :(得分:-2)
如果您在当前生命周期中创建了模型,则模型的wasRecentlyCreated属性将设置为true。否则,该属性将设置为false。
换句话说,假设您有一个用户,电子邮件为test@yopmail.com
$user = User::firstOrCreate(['email' => 'test@yopmail.com']);
var_dump($user->wasRecentlyCreated);
//以上将转储为false,因为该条目已存在,否则为true。