-
Notifications
You must be signed in to change notification settings - Fork 11.5k
[10.x] Set timestamps on Model::insert() #46791
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[10.x] Set timestamps on Model::insert() #46791
Conversation
86042ef
to
7965f88
Compare
How it is different from |
|
Insert is a low-level query builder method. You would need to use create to get full Eloquent features. |
@taylorotwell What do you think about a Model isn't Macroable and neither is Eloquent\Builder, right? Which I think is usually the project-level solution to this. Otherwise, it's extend the Model class and make sure everything within a project extends from it or add a trait to every model. Both are not ideal solutions. |
The thing is when you want to make something like this and attach Eloquent features like The existing Also I believe both EloquentBuilder and QueryBuilder are both macroable but you cant macro/overwrite existing functions afaik. |
Problem
Assume we have a model (
MyModel
) with timestamps. The following code inserts the data to the DB, but never sets the timestamps.The way around this is to explicitly set the
created_at
andupdated_at
columns.Solution
With this PR, if the Model uses timestamps, we'll set the created_at and/or updated_at columns to the current time upon calling Eloquent\Builder@insert()
Changes made to tests
For a number of Eloquent tests (especially those relying on Pivot models), no $timestamps property was ever set. I have updated those. I fear that this very necessity could be seen as the functionality being a breaking change. I personally don't think that it is, and was more or less oversight within the tests.
Final thoughts
It would be really nice to have a distinct method that casts all properties when doing an insert, rather than just the timestamps. Builder::insertWithCasts() could handle type juggling as well as timestamps. That way if client code needs to use an insert where the table has a json column, they don't have to remember to json_encode() the data. I would not tie it into the insert() method as it's computational waste to retrieve a model and cast properties.