Timestamps and soft deletes in laravel

Time to cover two awesome features of the Model class: timestamps and soft deletes. How many times have you had to manually handle the creation date of a record and its last update time? Model timestamps are here to help.

Also, how many times have you had to create a delete feature while maintaining some information about your data, if not at all? Yeah, the soft deleting feature is here to help too.

Timestamps

Do you remember the last method we called in our books table migrations? No?

here it is:

  Schema::create('books', function(Blueprint $table)
  {
    // other fields...

      $table->timestamps();
  });

Exactly, it is the timestamps() method. This special Schema Builder method is used to create two separate fields: created_at and updated_at, both MySQL DATETIME or equivalent. Eloquent automatically handles these two fields when you create or update a record.

It can be extremely useful: how many times did you have to deal with some last edit data on a specific table? Also, imagine how much easier it could be with these two fields to handle some scheduled article posting.

However, sometimes they are not so useful: you can disable them just by setting the timestamps property model to false.

  <?php

  namespace App;

  class Book extends Model {

      public $timestamps = false;

  }

Note

Obviously, if you plan to disable timestamps you can delete the corresponding timestamps() Schema Builder call in your migration. You are not going to need it anymore.

You can eventually specify the format of your timestamps, if needed. Here’s an example:

  <?php

  namespace App;

  class Book extends Model {

      protected $table = 'books'';

      protected function getDateFormat()
      {
          // returining a different timestamp format!
          return 'd/m/Y';
      }

  }

All you have to do is to implement the getDateFormat method in your model and let it return a string that describes the desired format.

Note

In the returned string, you can insert anything that is a valid format for the date() PHP function (you can find a complete reference at http://php.net/manual/en/function.date.php).

Soft deleting

The soft deleting feature is a really interesting feature that can be useful on many occasions.

If you decide to activate soft deleting, you will never really delete a record: instead, a deleted_at column will be updated with the date of the operation, but nothing more. Eloquent will work exactly like before but you will never lose anything.

It could be a perfect fit for an e-commerce database that handles orders. The customer could decide to clear his order history. However, in order to keep accounts perfect, the shop owner would continuously need every single order detail.

As you can easily imagine, from the previous chapter, in order to activate the soft deleting feature, you will have to make a call to softDeletes() Schema Builder method.

  Schema::create('books', function(Blueprint $table)
  {
    // other fields...

      $table->softDeletes();
  });

After this, you will have to include the SoftDeletes trait in the model.

  <?php

  namespace App;

  use IlluminateDatabaseEloquentSoftDeletes;

  class Book extends Model {

      use SoftDeletes;

      protected $dates = ['deleted_at'];

  }

Nothing more!

Also, working with soft deleted data is really easy. Let’s implement a simple example based on the situation we described before (the customer order’s details and shop owner’s need).

First of all, here’s an example model:

  <?php // Order.php

  namespace App;

  use IlluminateDatabaseEloquentSoftDeletes;

  class Order extends Model {

      use SoftDeletes;

      protected $dates = ['deleted_at'];

  }

In his/her order history, a customer should see only his/her existent orders and not deleted orders. I used quotation marks because we are talking about records that always exist.

  // getting all the orders

$orders = AppOrder::orderBy('created_at', 'desc')->get();

Nothing really special!

What about the shop owner? The magical word is withTrashed:

  // getting all the orders, including the "deleted" ones...

$orders = AppOrder::withTrashed()->orderBy('created_at', 'desc')->get();

The withTrashed method automatically includes every result that is actually present in the table, regardless of the deleted_at field value.

Also, if you need to see only the soft deleted fields, change withTrashed to onlyTrashed.

  $trashedOrders = AppOrder::onlyTrashed()->orderBy('created_at', 'desc')->get();

Finally, you can restore a record that has been deleted with the restore method.

  $trashedOrder = AppOrder::find($trashedOrderId);
  $trashedOrder->restore();

  // $trashedOrder is not so trashed anymore...

If you prefer, you can execute the restore operation using a query as a filter.

  AppOrder::where('customer_id', '=', $customerId)->restore();

Alright, I know what you are thinking: this feature is cool but what if I want to really delete a field?

No problem; just use forceDelete.

  order = AppOrder::find($orderId);

  // bye bye... forever :'(
  $order->forceDelete();

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares

Get the best in web dev

Join dunebook.com and recieve best in web dev , once a week FREE

An email has been Sent to your Inbox ! Please Confirm your Subscription :)