Book Image

Laravel 5 Essentials

By : Martin Bean
Book Image

Laravel 5 Essentials

By: Martin Bean

Overview of this book

Table of Contents (15 chapters)
Laravel 5 Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Deleting data


There are two ways of deleting records. If you have a model instance that you have fetched from the database, then you can call the delete method on it:

$cat = Cat::find(1);
$cat->delete();

Alternatively, you can call the destroy method, specifying the IDs of the records you want to delete, without having to fetch those records first:

Cat::destroy(1);
Cat::destroy(1, 2, 3, 4, 5);

Soft deletion

By default, Eloquent will hard-delete records from your database. This means, once it's deleted, it's gone forever. If you need to retain deleted data (that is, for auditing), then you can use soft deletes. When deleting a model, the record is kept in the database but instead a deleted_at timestamp is set, and any records with this timestamp set will not be included when querying your database.

Soft deletes can be easily added to your Eloquent model. All you need to do is include the trait:

use Illuminate\Database\Eloquent\SoftDeletes;
class Cat extends Model {
  use SoftDeletes;
  protected...