The executed code updateOrCreate is: / p>
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
public static function firstOrNew(array $attributes)
{
if ( ! is_null($instance = static::where($attributes)->first()))
{
return $instance;
}
return new static($attributes);
}
then the correct one would be:
$eventos = Eventos::updateOrCreate(
["id" => $id],
["nome" => $nome, "descricao" => $descricao, "id_usuario" => $id_usuario]
);
where the search is by its identification, even in its model has the wrong configuration, where id
does not have to stay inside $fillable
, because it is automatically generated by the bank, then:
class Eventos extends BaseModel
{
protected $table = "eventos";
const UPDATED_AT = 'atualizado_em';
const CREATED_AT = 'criado_em';
protected $dateFormat = 'U';
protected $fillable = ["nome","descricao", "id_thumbnail",
"local", "endereco", "place_id",
"data_hora_inicio", "data_hora_fim",
"responsavel", "telefone1",
"telefone2", "email", "site", "nota",
"status", "categoria",
"facebook_page_url", "id_usuario","preco"];
}
I would particularly do so:
$evento = Eventos::find($id);
if (!$evento)
{
$evento = new Eventos();
$evento->fill(["nome"=>$nome,"descricao"=>$descricao,"id_usuario"=>$id_usuario]);
}
else
{
$evento->fill(["nome"=>$nome,"descricao"=>$descricao]);
}
$evento->save();
You can also create a scope in your model
:
class Eventos extends BaseModel
{
protected $table = "eventos";
const UPDATED_AT = 'atualizado_em';
const CREATED_AT = 'criado_em';
protected $dateFormat = 'U';
protected $fillable = ["nome","descricao", "id_thumbnail",
"local", "endereco", "place_id",
"data_hora_inicio", "data_hora_fim",
"responsavel", "telefone1",
"telefone2", "email", "site", "nota",
"status", "categoria",
"facebook_page_url", "id_usuario","preco"];
public function scopeGeneration($query, $id, $values = array())
{
$m = $query->find($id);
if (!m)
{
$m = new Eventos();
}
else
{
unset($values['id_usuario']);
}
$m ->fill($values);
$m->save();
return $m;
}
}
How to use:
$values = ["nome"=>$nome,"descricao"=>$descricao,"id_usuario"=>$id_usuario];
$evento = Eventos::generation($id,$values);