2

I'm facing a problem with date fields format in Laravel on a Pivot Table. What I want to achive is to use "created_at" and "updated_at" fields in Unix time format INT(11) instead of the TIMESTAMP. I also tried to use a custom Pivot but without any luck. By now code works fine but it uses timestamp and not Unix as is supposed to.

Somewhere in my code I do this:

//[.. other stuff ...]

//update the relation wich references current user and group 1

$user->groups()->sync(array(1 => array('newsletter' => $newsletter)));

This is my code:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;

class User extends Model{
    public function groups() {
        return $this->belongsToMany('Group')->withTimestamps();
    }

    public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
        if ($parent instanceof Group) {
            return new UserGroup($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

class Group extends Model {
    public function users() {
        return $this->belongsToMany('User')->withTimestamps();
    }

    public function newPivot(Eloquent $parent, array $attributes, $table, $exists)
{
        if ($parent instanceof User) {
            return new UserGroup($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

class UserGroup extends Pivot 
{
protected function getDateFormat()
{
    return 'U';
}

public function getDates()
{
    return array(
    'created_at',
    'updated_at');
}
    public function user() {
    return $this->belongsTo('User');
}

public function group() {
    return $this->belongsTo('Group');
}

}

Thanks for your attention.

cardy
  • 103
  • 1
  • 10
  • You probably have to take a look at mutators and accesors in the laravel documentation. http://laravel.com/docs/eloquent#accessors-and-mutators – fmgonzalez Jun 20 '14 at 08:47
  • @fmgonzalezas as stated [here](http://laravel.com/docs/eloquent#date-mutators) for date fields you need to override the getDates() method as I already did. – cardy Jun 20 '14 at 10:00
  • Overriding `getDates()` in that way you don't get anything. `created_at` and `updated_at` are already included in the `$dates` array. I think you need to return an empty array and create your own mutators-accesors to this fields to set-get Unixtimestamps. – fmgonzalez Jun 23 '14 at 07:10

0 Answers0