Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why soft deleted entities appear in query results?

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?

like image 819
Sergey Sob Avatar asked Aug 04 '13 08:08

Sergey Sob


2 Answers

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(); 
like image 70
Anshad Vattapoyil Avatar answered Sep 19 '22 02:09

Anshad Vattapoyil


The soft deleting feature works when using Eloquent. If you are querying the results with query builder you will eventually see all the records trashed and not trashed.

It is not clear in the current docs of Laravel 4, but seeing that the concept of soft deleting just appears under Eloquent ORM - Soft Deleting and not under Query Builder, we can only assume that: soft delete only works with Eloquent ORM.

like image 26
Rubens Mariuzzo Avatar answered Sep 20 '22 02:09

Rubens Mariuzzo