You can delete data after writing it to the database. You can either delete a model instance if you have retrieved one, or specify conditions for which records to delete.
To delete a model instance, retrieve it and call the delete()
method:
$user = User::find(1);
$user->delete();
Alternatively, you can specify a primary key (or an array of primary keys) of the records you wish to delete via the destroy()
method:
User::destroy(1);
User::destroy([1, 2, 3]);
You can also combine querying with deleting:
User::where('age', '<', 21)->delete();
This will delete all users who match the condition.
Note: When executing a mass delete statement via Eloquent, the
deleting
anddeleted
model events will not be fired for the deleted models. This is because the models are never actually retrieved when executing the delete statement.
Some times you don’t want to permanently delete a record, but keep it around for auditing or reporting purposes. For this, Eloquent provides soft deleting functionality.
To add soft deletes functionality to your model, you need to import the SoftDeletes
trait and add it to your Eloquent model class:
namespace Illuminate\Database\Eloquent\Model;
namespace Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
}
When deleting a model, it will set a timestamp on a deleted_at
timestamp column in the table for your model, so be sure to create the deleted_at
column in your table first. Or in migration you should call softDeletes()
method on your blueprint to add the deleted_at
timestamp. Example:
Schema::table('users', function ($table) {
$table->softDeletes();
});
Any queries will omit soft-deleted records. You can force-show them if you wish by using the withTrashed()
scope:
User::withTrashed()->get();
If you wish to allow users to restore a record after soft-deleting (i.e. in a trash can-type area) then you can use the restore()
method:
$user = User::find(1);
$user->delete();
$user->restore();
To forcefully delete a record use the forceDelete()
method which will truly remove the record from the database:
$user = User::find(1);
$user->forceDelete();