I have a table of Advertisements
, I need to delete a record temporarily that can be enabled again and I can also fetch the deleted results.
You just need to add soft delete trait in your Advertisement.php (Advertisement model)
For soft delete:
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Advertisement extends Eloquent {
use SoftDeletingTrait;
.....
}
Next, you need to add a column in table deleted_at (timestamp, default null), now when you normally delete your Advertisement
$advertisement = Advertisement::find($id);
$advertisement->delete();
It will add current timestamp in deleted_at column, and that particular row will not be fetched until deleted_at column has value.
For get all soft deleted values:
$deletedAdvertisement = Advertisement::onlyTrashed()->get();
you can use documentation for more info:
If you have created your table using migrations you need to add this to the migration file :
$table->softDeletes();
here's more about migrations : http://laravel.com/docs/4.2/migrations#creating-migrations
One the migration created and run you need to attach your table to a an Ad
model and your model need to use SoftDeletingTrait
like this :
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Ad extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
// ...
}
And now when querying the model "deleted" models will not be included in query results, if you want so, you could you withTrashed()
method like this :
Ad::withTrashed()->all();
if you want only the deleted one use :
Ad::onlyTrashed()->all();
For more info about soft deleting : http://laravel.com/docs/4.2/eloquent#soft-deleting