Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Model::updateOrCreate() update a soft-deleted model if the criteria matches?

Let's say I have a model that was soft-deleted and have the following scenario:

// EXISTING soft-deleted Model's properties
$model = [
    'id'         => 50,
    'app_id'     => 132435,
    'name'       => 'Joe Original',
    'deleted_at' => '2015-01-01 00:00:00'
];

// Some new properties
$properties = [
    'app_id'     => 132435,
    'name'       => 'Joe Updated',
];

Model::updateOrCreate(
    ['app_id' => $properties['app_id']],
    $properties
);

Is Joe Original now Joe Updated?

OR is there a deleted record and a new Joe Updated record?

like image 212
ryanwinchester Avatar asked Jul 16 '15 23:07

ryanwinchester


People also ask

How would you implement soft delete in laravel with example?

To soft delete a model you may use: $model = Contents::find( $id ); $model->delete(); Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL .

What is soft deleting in laravel?

Soft delete hides information from end-user or flags data as deleted while it still remains visible or active in your database. To perform soft delete in Laravel, you need to have a deleted_at column that should be set to default null , as it should be of timestamp data type in the model.

What is withTrashed in laravel?

Laravel, “withTrashed()” linking a deleted relationship With Eloquent we can define the relation easily. If the user gets deleted, and on the User model we use the SoftDeletes trait, you can use withTrashed() method here.


1 Answers

$variable = YourModel::withTrashed()->updateOrCreate(
    ['whereAttributes' => $attributes1, 'anotherWhereAttributes' => $attributes2],
    [
        'createAttributes' => $attributes1,
        'createAttributes' => $attributes2,
        'createAttributes' => $attributes3,
        'deleted_at' => null,
    ]
);

create a new OR update an exsiting that was soft deleted AND reset the softDelete to NULL

like image 85
Mhar Daniel Avatar answered Oct 07 '22 07:10

Mhar Daniel