Laravel Pivot table optional date and time field format (no timestamp) using a carbon object

I have a pivot table ('offer_usage_detail') in my application, a table with 4 fields 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 a list of users who used the offer with the date and time in format d-m-Y H:i.

So, I added the code below in my sentence model

 public function user() {
    return $this->belongsToMany('User', 'offer_usage_detail', 'offer_id', 'user_id')->withPivot('use_time');
}

I am currently using the core php datec function strtotimeto format the date, but I want to know if there is a way to convert date table pivot tables to a carbon object.

I tried to put the box use_timein Offer Model protected $dates = array('created_at','use_time');, but that didn't work.

Can an extra column column be converted to a carbon object if a date column field is specified?

+4
1

, , - :

// 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
+5

Source: https://habr.com/ru/post/1547413/


All Articles