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?
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.
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.
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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With