in our project we must be use soft delete for each posts. in laravel document i think we can only use this feature for tables.
can we use that for posts on table such as
$id = Contents::find($id); $id->softDeletes();
To soft delete a model you may use: $model = Contents::find( $id ); $model->delete(); Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL .
Soft deleting the data allows us to easily view and restore the data with minimal work and can be a huge time saver when data is accidentally deleted. Laravel provides support for soft deleting using the Illuminate\Database\Eloquent\SoftDeletes trait.
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; protected $table = 'posts'; // ... }
When soft deleting a model, it is not actually removed from your database. Instead, a
deleted_at
timestamp is set on the record. To enable soft deletes for a model, specify thesoftDelete
property on the model (Documentation).
use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required class Post extends Eloquent { use SoftDeletingTrait; protected $table = 'posts'; // ... }
For example (Using a posts
table and Post
model):
class Post extends Eloquent { protected $table = 'posts'; protected $softDelete = true; // ... }
To add a deleted_at column to your table, you may use the
softDeletes
method from a migration:
For example (Migration class' up
method for posts
table) :
/** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function(Blueprint $table) { $table->increments('id'); // more fields $table->softDeletes(); // <-- This will add a deleted_at field $table->timeStamps(); }); }
Now, when you call the delete
method on the model, the deleted_at
column will be set to the current timestamp
. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete
a model you may use:
$model = Contents::find( $id ); $model->delete();
Deleted (soft) models are identified by the timestamp
and if deleted_at
field is NULL
then it's not deleted and using the restore
method actually makes the deleted_at
field NULL
. To permanently delete a model you may use forceDelete
method.
You actually do the normal delete. But on the model you specify that its a softdelete model.
So on your model add the code:
class Contents extends Eloquent { use SoftDeletingTrait; protected $dates = ['deleted_at']; }
Then on your code do the normal delete like:
$id = Contents::find( $id ); $id ->delete();
Also make sure you have the deleted_at
column on your table.
Or just see the docs: http://laravel.com/docs/eloquent#soft-deleting
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