以下是原始接受的答案:Laravel-4 https://stackoverflow.com/questions/tagged/laravel-4
已经有方法了findOrFail
可用于Laravel
当使用这个方法时它会抛出ModelNotFoundException
失败,但在您的情况下,您可以通过在模型中创建一个方法来实现,例如,如果您有一个User
模型,然后你只需将此函数放入模型中
// Put this in any model and use
// Modelname::findOrCreate($id);
public static function findOrCreate($id)
{
$obj = static::find($id);
return $obj ?: new static;
}
从您的控制器中,您可以使用
$user = User::findOrCreate(5);
$user->first_name = 'John';
$user->last_name = 'Doe';
$user->save();
如果用户与id
of 5
存在,那么它将被更新,否则将创建一个新用户,但id
将last_user_id + 1
(自动递增)。
这是做同样事情的另一种方法:
public function scopeFindOrCreate($query, $id)
{
$obj = $query->find($id);
return $obj ?: new static;
}
您可以使用scope
在模型中,所以方法在Model
将scopeMethodName
并打电话Model::methodName()
,与您在静态方法中所做的相同,例如
$user = User::findOrCreate(5);
Update:
The firstOrCreate
可用于Laravel 5x
,答案太旧了,它是为Laravel-4.0
in 2013
.
在 Laravel 5.3 中,firstOrCreate
方法有以下声明:
public function firstOrCreate(array $attributes, array $values = [])
这意味着您可以像这样使用它:
User::firstOrCreate(['email' => $email], ['name' => $name]);
仅通过电子邮件检查用户的存在,但创建后,新记录将保存电子邮件和姓名。
API Docs https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Builder.html#method_firstOrCreate