Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tedmasterweb's avatar

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

0 likes
6 replies
SaeedPrez's avatar
Level 50

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'
    ]
)
tedmasterweb's avatar

Excellent suggestions. I've implemented the version 7 option. Thanks!!!

1 like
djkarimi's avatar

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;
}
1 like
xdega's avatar

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?

hunglam's avatar

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'
    ]
)
ualihandulat's avatar

what ? It,s very easy.

$unit = Unit::whereDate('created_at', date('Y-m-d'))->updateOrCreate([], [ 'name' => 'hello' ]);

1 like

Please or to participate in this conversation.