updateOrCreate - Match created_at (just the date part)
Does anyone know how to use updateOrCreate where one of the keys is created_at and the value to match is just the date part of the field? For example:
Unit::updateOrCreate(
[
'created_at' => '2016-05-11'
],
[
'name' => 'hello'
]
)
This isn't working for me because created_at is a datetime and apparently the equivalency is '=' when using updateOrCreate.
TIA
I guess you could do something like this..
If you have PHP 7+
Unit::updateOrCreate(
[
'created_at' => Unit::where('created_at', 'LIKE', '2016-05-11 %')->first()->created_at ?? null
],
[
'name' => 'hello'
]
)
If you have PHP 5.x
$date = Unit::where('created_at', 'LIKE', '2016-05-11 %')->first();
$date = is_null($date) ? null : $date->created_at;
Unit::updateOrCreate(
[
'created_at' => $date
],
[
'name' => 'hello'
]
)
Excellent suggestions. I've implemented the version 7 option. Thanks!!!
Add new function code :)
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php :
public function updateOrInsert(array $attributes, array $values = [])
{
$instance = $this->where($attributes);
if ($instance->count() != 0) {
$instance->update($values);
} else {
$instance = $this->updateOrCreate($attributes, $values);
}
return $instance;
}
Sorry to necro, but I have the same issue and @SaeedPrez solution (PHP 7+) gives me a parse error in vscode.
Does anyone else have this issue?
I did it, I wanted to write to people after finding it.
I've read @saeedprez and edited it, it worked (PHP 7+)
Unit::updateOrCreate(
[
'created_at' => Unit::where( DB::raw('DATE(DATE_FORMAT(created_at , \'%Y-%m-%d\'))'),'2016-05-11')->first()->created_at ?? '2016-05-11'
],
[
'name' => 'hello'
]
)
what ? It,s very easy.
$unit = Unit::whereDate('created_at', date('Y-m-d'))->updateOrCreate([], [
'name' => 'hello'
]);
Please or to participate in this conversation.