Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a model uses soft deletes in Laravel 4.2

How do I determine if a model uses soft deletes in Laravel 4.2?

In the Laravel API I found the function isSoftDeleting(), but apparently that was removed from Laravel 4.2 now that it uses the SoftDeletingTrait.

How would I go about determining if a model uses soft deletes now?

like image 706
Chris Avatar asked Aug 05 '14 14:08

Chris


People also ask

How soft delete is implemented 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 the advantage of soft delete in Laravel?

The advantage of soft-delete concept is, as you never physically delete the data, there is no risk of loss of data when something goes wrong (with the delete action, not with your code). It's easy to get back the record by just changing the flag.

What are soft deletes?

soft deletion (plural soft deletions) (databases) An operation in which a flag is used to mark data as unusable, without erasing the data itself from the database.


2 Answers

If you want to check programatically whether a Model uses soft deletes you can use the PHP function class_uses to determine if your model uses the SoftDeletingTrait

// You can use a string of the class name
$traits = class_uses('Model');
// Or you can pass an instance
$traits = class_uses($instanceOfModel);

if (in_array('SoftDeletingTrait', $traits))
{
    // Model uses soft deletes
}

// You could inline this a bit
if (in_array('SoftDeletingTrait', class_uses('Model')))
{
    // Model uses soft deletes
}
like image 154
RMcLeod Avatar answered Oct 22 '22 08:10

RMcLeod


I needed to detect soft deletion on a model where the trait had been included in a parent class, so class_uses() did not work for me. Instead, I checked for the bootSoftDeletingTrait() method. Something along the lines of:

// Class Name $usesSoftDeletes = method_exists('User', 'bootSoftDeletingTrait');

or

// Model Instance $usesSoftDeletes = method_exists($model, 'bootSoftDeletingTrait');

should work.

like image 3
Ben Batschelet Avatar answered Oct 22 '22 07:10

Ben Batschelet