Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel pivot table timestamps

I have a small question about Laravel's pivot table and it's timestamps (created_at/updated_at).

The scenario is:

assign many tickets to many users, and see when it was assigned.

I want to keep the created_at timestamp, but want to get rid of the updated_at column when creating the migration.

In my research I've stumbled upon the solution to declare public $timestamps = false; in the model. But a pivot table does not have a model - and it will disable both created_atand updated_at.

Other than this I haven't found any results that matches my case.

Can anyone enlighten me here? Thanks


2 Answers

Update

From Laravel 5 you can just fix this issue and maintain your time stamps in your pivot table using withTimestamps() like that.

return $this->belongsToMany('App\Role')->withTimestamps();

https://laravel.com/docs/5.1/eloquent-relationships#many-to-many

like image 138
Amr Ezzat Avatar answered Nov 18 '25 13:11

Amr Ezzat


But a pivot table does not have a model

This is not true. From the Laravel docs:

If you would like to define a custom model to represent the intermediate table of your relationship, you may call the using method when defining the relationship. Custom many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\Pivot class while custom polymorphic many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\MorphPivot class.

To do this, just create a model for your pivot table and then the rest of the steps are pretty much the same as they would be for a usual model.

You can set const UPDATED_AT = null; to only use created_at. More details in this SO thread

like image 43
Paras Avatar answered Nov 18 '25 13:11

Paras