Currently we have firstOrCreate
or firstOrNew
, but I don't think they really fit your needs. For instance, firstOrCreate
will try to locate a row by all attributes, not just some, so an update in this case wouldn't make sense. So I think you really would have to find it, but you can create a BaseModel and create a createOrUpdate method that could look like this:
This is untested code
class BaseModel extends Eloquent {
public function createOrUpdate($attributes, $keysToCheck = null)
{
// If no attributes are passed, find using all
$keysToCheck = $keysToCheck ?: $attributes;
if ($model = static::firstByAttributes(array_only($keysToCheck, $attributes))
{
$model->attributes = $attributes;
$model->save();
}
else
{
$model = static::create($attributes);
}
return $model;
}
}
This is an implementation of it:
class Post extends BaseModel {
public function store()
{
$model = $this->createOrUpdate(Input::all(), ['full_name']);
return View::make('post.created', ['model' => $model]);
}
}