Laravel Pivot table extra date-time field format (Not timestamp) using carbon object

eloquent, laravel, laravel-4, php

Solution

The best solution I would suggest is creating custom pivot model for this relation:

// Offer model (the same goes for the User model, but change to 'instanceof Offer`
public function newPivot(Eloquent $parent, array $attributes, $table, $exists)
{
    if ($parent instanceof User) return new OfferUserPivot($parent, $attributes, $table, $exists);

    return parent::newPivot($parent, $attributes, $table, $exists);
}

// OfferUserPivot
use Illuminate\Database\Eloquent\Relations\Pivot;

class OfferUserPivot extends Pivot {
   // override either property:
   protected $dates = ['use_time'];

   // or method:
   // public function getDates()
   // {
   //   return ['use_time']; // and other columns like created_at etc if you like
   // }
}

// Then you can do this:
$user->offers->first()->pivot->useTime; // Carbon object
$offer->users->first()->pivot->useTime; // Carbon object

Problem

I have a pivot table ('offer_usage_detail') in my app, table having 4 field as below ``` id int AutoIncrement user_id int reference to user table offer_id int reference to offer table use_date date-time Store date time when user use offer ``` I need to show list of user who used offer with date and time in `d-m-Y H:i` format. So i added below code in my offer model ``` public function user() { return $this->belongsToMany('User', 'offer_usage_detail', 'offer_id', 'user_id')->withPivot('use_time'); } ``` Currently i m using core php's `date` function with `strtotime` to format date time, But i want to know is there any way to convert Pivot tables date time fields to carbon object. I tried putting `use_time` field in `Offer Model`'s `protected $dates = array('created_at','use_time');` but it didn't worked. Is it possible to convert extra pivot table column to carbon object if column is date time field?

Original source