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
)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With