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

jostrander's avatar

Model::firstOrNew() with soft deleted.

I am looking to find all objects whether trashed or not using the firstOrNew if possible.

function testMethod() {
    $entity = Entity::firstOrNew('uuid' => $uuid); // This doesn't include trashed (as it shouldn't, but is it possible to have it find them?)
    $entity->property = $newPropertyValue;
    if ($entity->trashed()) {
        $entity->restore();
    }
    $entity->save();
}
0 likes
7 replies
JarekTkaczyk's avatar

@magikman Just don't use static firstOrNew but simply call the same as the method does:

$attributes = ['field' => 'value', ...];

$entity = Entity::where($attributes)->withTrashed()->first() ?: new Entity($attributes);

if ($entity->trashed()) $entity->restore();
3 likes
magikman's avatar

Thanks @JarekTkaczyk it's the perfect solution when you have primary key but when you have composite primary keys it simply fails right ?

JarekTkaczyk's avatar

@magikman Well, Eloquent fails with composite primary keys in general. Every ORM has some issues with this, even Doctrine forces constraints if you want to use composite keys.

rcadhikari's avatar

Try this:

$entity = Entity::withTrashed()->firstOrNew('uuid' => $uuid);

Also to restore:

$entity = Entity::withTrashed()->firstOrNew('uuid' => $uuid)->restore();
1 like

Please or to participate in this conversation.