Why soft deleted entities appear in query results?

Sergey Sob picture Sergey Sob · Aug 4, 2013 · Viewed 47.2k times · Source

I am trying to implement soft deleting concept.

Here is my object:

class Post extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'posts';
    protected $softDelete = true;

    ...

Soft delete is on.

Now, if I 'delete' a post, it gets a 'deleted_at' timestamp:

description

The problem is, when I search or just use all() to display the posts, the soft deleted items appears there. What is wrong?

Answer

devo picture devo · Oct 21, 2013

Sometimes, you will get the soft deleted table entries with get() even with eloquent and protected $softDelete = true;.

So to avoid this problem, use

...->whereNull('deleted_at')->get();

For example, this query will fetch all rows including soft deleted.

DB::table('pages')->select('id','title', 'slug')
                                   ->where('is_navigation','=','yes')
                                   ->where('parent_id','=',$parent_id)
                                   ->orderBy('page_order')
                                   ->get();

So the proper method is,

DB::table('pages')->select('id','title', 'slug')
                                   ->where('is_navigation','=','yes')
                                   ->where('parent_id','=',$parent_id)
                                   ->whereNull('deleted_at')
                                   ->orderBy('page_order')
                                   ->get();