Search code examples
phplaraveltraitssoft-delete

Using soft delete in laravel 5 issue


This is my model:

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Image extends Model
{
    use SoftDeletes;
    //table
    protected $table = 'images';
}

If I add my trait I cannot find any record if I use my model like this:

$imageFile = ImageModel::where('id', 12)->first();

The $imageFile is always null, if I remove my trait is working . Why ???


Solution

  • From what you've said, it is working as intended. When you use the soft-delete trait in Laravel, the model is NOT deleted from the DB. When you pass the model to destroy(), the only thing that happens is that the deleted_at field becomes non-null.

    If you look deeper into Laravel's code, when you call

    ImageModel::where('id', 12)->first(); 
    

    the softdelete trait is adding

    where null
    

    to the SQL for the deleted_at column. This means that, as you said, if you turn off the trait, $imageFile will not be null (it is working). Because the softdelete never deleted the model from the DB - it just added a non-null value to the DB for that model and is thus visible to a normal laravel query: when you don't use softdeletes, Laravel doesn't care about the deleted_at field so it sees the model. When you turn softdeletes on, it looks for null values only, and because your model was softdeleted (it has a non-null value), it returns $imageFile as null.

    As bytewave said, to properly use the softdeletes to NOT return a null value to $imageFile, you would need to add in the softdeleted models to your query like so:

    Image::withTrashed()->where('id', 12')->first();
    

    I think you were looking for slightly different functionality (a roll-back), which is a little different from the softdelete trait's intention. The manual is pretty good: 5.4 soft-deletes, but looking deeper into the trait code might help as well.

    Take a look at the ->restore() function as well - this might help you get closer to the intended roll-back you were looking for. But, you need the logic up-front first to know which were deleted.