38

I have the following code:

$entry->save();

$categories = [];

$categories[Input::get('main_category')] = ['main' => 1];

for ($i=1; $i<=4 ; ++$i) {
    $input = Input::get('category_'.$i);
    if ($input != '') {
            $categories[$input] = ['main' => 0];
    }
}



$entry->categories()->sync($categories);

$inTags = explode(',', trim( Input::get('tags'), ','));
$tags = [];

foreach ($inTags as $tag) {
    $tag = trim($tag);
    if ($tag == '') {
        continue;
    }
    $fTag = Tag::firstOrCreate(array('name' => $tag));

    $tags[$fTag->id] = ['entry_id' => $entry->id];
}
$entry->tags()->sync($tags);

In above code I create entry ($entry->save() is here just enough to understand it, earlier code is not important), then save to which categories this entry belongs to (using pivot table) and do the same with tags (but for tags if tag doesn't exist I create one).

However in both pivot tables created_at field is left default (0000-00-00 00:00:00) after inserting data (probably the same will be with updated_at but I haven't tested it ).

Do I need somehow activate filing timestamps automatically or need I fill them manually on my own (but probably it will mean much more coding and no using sync)?

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • 4
    You are providing `sync` with associative array, while it accepts an array of `ids` to sync. And for the timestamps on your pivot table - you need to use `withTimestamps()` on the relation definition, otherwise those won't be set/updated. – Jarek Tkaczyk Sep 26 '14 at 12:37
  • @JarekTkaczyk Thanks `withTimestamps()` solved the issue. But using `sync` you can add extra pivot data - look at http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables and section `Adding Pivot Data When Syncing` – Marcin Nabiałek Sep 26 '14 at 12:47
  • Yeah, you can do that, if it's pivot data. I thought you passed there one of the relation keys. – Jarek Tkaczyk Sep 26 '14 at 12:48
  • You was right about it, I had my relationship defined with wrong foreign key for tags – Marcin Nabiałek Sep 26 '14 at 15:21

1 Answers1

95

In order to handle pivot timestamps when you sync/attach belongsToMany relation, you need to include withTimestamps() on the relation definition:

// some model
public function someRelation()
{
  return $this->belongsToMany('RelatedModel')->withTimestamps();
}

Then every sync/attach/updateExistingPivot will set/update the timestamps on your pivot table.

hatef
  • 5,491
  • 30
  • 43
  • 46
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157