Laravel 5.2 - How to update "updated_at" field with UTC timestamp? - laravel-5

I'm using Laravel 5.2 (on PHP version 7) and below is the update query I'm running:
$data=DB::table('posts')
->where("id", $post_id)
->update(
array(
'title' => $request['title'],
'body' => $request['body'],
'slug' => str_slug($request['title']),
'updated_at' => DB::raw('CURRENT_TIMESTAMP')
));
The "updated_at" field updated with the current time. But I want to update it with the UTC timestamp. How can I achieve this?

If you use the model->save() method it should handle created and updated dates for you. In general you should not need to do raw DB updates in Laravel.
If you wish to have a different timezone for this then look at the timezone setting in app.php. The default however is 'UTC' so you should not have to worry.

Related

timestamp column is not in ISO 8601 format

I want all the dates from the server to be sent in the ISO 8601 standard in Laravel. Laravel version is 9. The created_at and updated_at columns are sent in the wanted format but my custom column is not in that format.
Here is the code of the Seeder
"questions_updated_at" => Carbon::now()->format('Y-m-d H:i:s'),
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
"updated_at" => Carbon::now()->format('Y-m-d H:i:s')
Also tested with now()
In MySQL their values are same. Migration
$table->timestamp("questions_updated_at");
$table->timestamps();
In the Model. protected $dateFormat = \DateTime::ISO8601;
In Controller return response(MyClass::where('show_on_front', true)->get());
And in Postman getting it like this.
[{
"questions_updated_at": "2022-11-16 15:02:44",
"created_at": "2022-11-16T15:02:44.000000Z",
"updated_at": "2022-11-16T15:02:44.000000Z"
}]
In app.php the time zone is 'timezone' => 'UTC'
Help will be appreciated.
You have to use casts in order to change the type of the data fetched from the data,
in the model file
protected $casts = [
'questions_updated_at' => 'datetime',
];
the timestamp is stored as timestamp and it is fetched as string from database , casts is used to change it to the prefered DateTime format , the created_at and updated_at are already casted in HasAtttributes trait

Why are multiple rows ('versions') saved with eloquent, when I only edit one

I use a versioning system to save multiple versions of a 'minor' (a model in my application). It contains quite a few fields, like name, goals, requirements, subject and many more. When I save a new version, or 'version 2', using eloquent, it also changes the other version.
I have tried multiple ways of saving the minor, like requesting the first one and updating it like below, or changing each individual item one-by-one.
Minor::limit(1)
->where("id", $id)
->where('version', $_POST['version'])
->first()
->update([
'name' => $_POST['name'],
'ects' => floatval($_POST['ects']),
'contact_hours' => intval($_POST['contact_hours']),
'education_type' => $_POST['education_type'],
'language' => $_POST['language'],
'subject' => Input::get('subject'),
'goals' => Input::get('goals'),
'requirements' => Input::get('requirements'),
]);
It should only save the selected version, but instead, it overwrites all versions of the minor with the same ID and saves them to the database.
How can I prevent this, or does anyone have an idea on how to fix this?
You can try using updateOrCreate method:
Minor::updateOrCreate([
'id' => $id,
'version' => $_POST['version']
],[
'name' => $_POST['name'],
'ects' => floatval($_POST['ects']),
'contact_hours' => intval($_POST['contact_hours']),
'education_type' => $_POST['education_type'],
'language' => $_POST['language'],
'subject' => Input::get('subject'),
'goals' => Input::get('goals'),
'requirements' => Input::get('requirements'),
]);
I still don't know why this happened or how to fix it using the same method. I have however found a way around it. I now update and save the minor with the ->update([...]) method build into eloquent.
Minor::where([["id", "139858"], ["version", Input::get('version')]])
->update([
'name' => Input::get('name'),
'ects' => Input::get('ects'),
'contact_hours' => Input::get('contact_hours'),
'education_type' => Input::get('education_type'),
'language' => Input::get('language'),
'subject' => Input::get('subject'),
'requirements' => Input::get('requirements'),
'goals' => Input::get('goals')
]);
This doesn't seem to alter the other versions. This is the only way I found to make it work, you can't make a variable of the object, change values and then save it. That would overwrite the other versions.

Laravel updateOrCreate Timestamp Updating Issue

I am using the updateOrCreate method to check whether data has been changed from a response which is entered in the DB. If the record is new then it successfully adds the correct timestamp. However, I have noticed that the updated timestamp updates record for all of the records. I want this to only update if records have been updated.
But looking at the issue I believe all the records are being updated regardless.
if (isset($customers->Data)) {
foreach ($customers as $customerData) {
if ($customer = $customerData->attributes()) {
if ((string) $customer->CustomerType !== 'A') continue;
if ((string) $customer->CustomerEmail === '') continue;
$customerDb = $this::updateOrCreate(
[
'email' => $customer->CustomerEmail,
'code' => $customer->Customer,
'currency' => $customer->Currency,
],
[
'email' => $customer->CustomerEmail,
'code' => $customer->Customer,
'currency' => $customer->Currency,
'name' => $customer->CustomerName,
'phone' => $customer->CustomerPhone,
'terms' => $customer->Terms,
]
);
}
}
}
The email, code, currency fields will always be unique and the rest to create if these are not present. Should the default behavior be that it updates regardless? What I want to achieve is to only detect if a record has been changed if it has then updated that particular field and update the timestamp if it's not there then create it. Thus filtering out what has been updated and only show these records rather than the whole table.
Sorry but new to Laravel any guidance is welcome thank you.

updateOrCreate isn't filling all the fields in Laravel 5.6

I have a code:-
$tokenUpdated = AppToken::updateOrCreate(
array(
'user_id' => $user_id, 'token' => $token),
array('expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at)
);
Though new rows are being inserted, the expiry, created_date fields values aren't getting saved. They records show NULL value which are default values.
What am I doing wrong?
First you need to check if expiry and created_date are returning values, if so then you could use the updateOrCreate function like this:
$tokenUpdated = AppToken::updateOrCreate(
['user_id' => $user_id, 'token' => $token]
['expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at
]
);
check laravel eloquent documentation: https://laravel.com/docs/5.6/eloquent

Laravel Eloquent - Inserting multiple records

How do we insert multiple records using eloquent in Laravel?
Basically this:
Teacher::create([
'user_id' => $user->id,
'college_id' => $collegeId,
'first_name' => $this->faker->firstName(),
'last_name' => $this->faker->lastName()
],[...],[...]);
Okay, I just came across the github request where Taylor replied that it is not possible with Eloquent and to use Query builder instead.
Here is the link to the issue:
https://github.com/laravel/framework/issues/1295

Resources