soft delete not working when $dateFormat="U" - laravel

Im trying to import softDelete to current project. In migration file i added:
$table->softDeletes();
In model. I got this:
protected $dateFormat = 'U';
But deleting not working as i expected.
Invalid datetime format: 1292 Incorrect datetime value: '1579188678' for column 'deleted_at'
So my question is how can i use deleted_at as unix time or how to use deleted_at column as timestamp when protected $dateFormat = 'U'; this was still exist. Thanks in advance.

Since you want to use the Unix timestamp as format, you can't use the ->sofDeletes() and ->timestamps() methods in migration, you need to set them yourself as integers
$table->integer('created_at')->nullable();
$table->integer('updated_at')->nullable();
$table->integer('deleted_at')->nullable();

Related

How to set 24 hour time in laravel migration

I have an input field that will provide me the 24 hour format time like 16:30, 18:22, 13:50 etc. So how to set migration column for this.
I read already documentation but not did not understand.
As #M Khalid Junaid has suggested, you should define a mutator for your attribute on your model to modify the value of a normal timestamp.
So firstly, you need to create the column in the migration:
$table->timestamp('your_column_name');
Then, you can create your mutator on your model just like any method. We are going to use Carbon to play around with the format. Keep in mind that the name of the mutator needs to be the camelCase of your column name:
protected function yourColumnName(): Attribute
{
return new Attribute(
get: fn ($value) => Carbon::parse($value)->format('H:i'),
);
}

Laravel Eloquent suddenly started echoing this error: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value

Before thinking it's duplicate: Inside the $request->input('birthdate') variable, the date format is correct; for example is '1979-02-11'.
Even so, I get that error:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '11/02/1979' for column 'birthdate' at row 1 (SQL: insert into users (birthdate, updated_at, created_at) values (11/02/1979, 26/06/2020, 26/06/2020))
Something about it has already been discussed in this GitHub post.
My application was doing fine. I guess after executing the $ composer update and then carrying on with the development when I was testing the register part, that error showed up.
I haven't found out why now inside the Laravel application the date formats are changed to 'mm/dd/yyyy'. In the request, the date format is as it should: 'yyyy-mm-dd'.
In the User.php model file I had originally:
protected $dates=['birthdate'];
/*My bad. I hadn't realized I probably added without noticing, the following piece of code*/
/**
* Date format
*
* #var array
*/
protected $dateFormat='d/m/Y';
And I have changed it to (according to that same post:
protected $casts = [
'email_verified_at' => 'datetime',
'birthdate' => 'date:Y-m-d'
];
However, the error is still there even if I try with $ php artisan tinker and store the $user->birthdate='1960-05-22';.
Psy Shell v0.10.4 (PHP 7.4.5 — cli) by Justin Hileman
>>> $user = new App\Models\User;
=> App\Models\User {#3358}
>>> $user->birthdate = '1960-05-22';
=> "1960-05-22"
>>> $user->save();
Illuminate/Database/QueryException with message 'SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '22/05/1960' for column 'birthdate' at row 1 (SQL: insert into `users` (`birthdate`, `updated_at`, `created_at`) values (22/05/1960, 26/06/2020, 26/06/2020))'
>>>
In the migration file I have declared the birth date column as follows:
$table->date('birthdate')->nullable()->comment('Birthdate');
What is going wrong now? Can anyone help?
EDIT - Fixed
My bad. I hadn't realized I probably added without noticing, the following piece of code:
//protected $dateFormat='d/m/Y';
protected $dateFormat='Y-m-d';
So I commented it out.

Laravel Carbon allow trailing data at Postgresql Timestamp

I have some timestamp records on the DB that have trailing milliseconds at the timestamp and some not have. How to allowing that trailing data (millisecond) in carbon? Is this possible?
Here's the sample of my data
I can't always change the data manually because there are some other services using the same database and sometimes storing timestamp with trailing milliseconds.
As you are using Postgres, your timestamp probably has TIME WITH TIMEZONE
Example: "2018-04-19 07:01:19.929554".
In Such case have to add a date Mutator to your Model.
In your Model add this field for date mutator:
protected $dateFormat = 'Y-m-d H:i:sO';
Alternate Solution:
As you have a mix of timestamps with and without milliseconds I suggest you try this solution using Laravel field mutators:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Parse the created at field which can optionally have a millisecond data.
*
* #param string $created_at
* #return Carbon::Object
*/
public function getCreatedAtAttribute($created_at)
{
// Try to remove substring after last dot(.), removes milliseconds
$temp = explode('.', $created_at);
// If created_at had milliseconds the array count would be 2
if(count($temp) == 2) {
unset($temp[count($temp) - 1]); // remove the millisecond part
} else {
$temp = [$created_at]; // created_at didnt have milliseconds set it back to original
}
return Carbon::parse(implode('.', $temp))->format('Y-m-d H:i:s')
}
}
I have observed in Laravel, storing datetime in database ignores
millisecond field, probably depends on version and db server type.
Also Laravel has whereData() and whereTime() query builders but we
need something like whereDateTimeTz() in all cases.
I recommend storing datetime as unix timestamps in database.
From user timezone convert to GMT and save it to db as millis-timestamp
Carbon::parse('date', 'user_timezone')->setTimezone('GMT')->getPreciseTimestamp(3);
While displaying just convert the db timestamp (GMT) back to user timezone including DST status.
Laravel 7 provides better date parsing by falling back to Carbon::parse if the recevied timestamp from the database doesn't match the expected $dateFormat.
PR: https://github.com/laravel/framework/pull/30628

Laravel: set timestamps from datetime to now as int

I am creating a Laravel application. Earlier I used to design the database with the datetime datatypes for created_at and updated_at, but a friend of mine suggested me that I should use timestamp instead of datetime because it's good with different timezones.
Is this a good idea to use timestamp instead of datetime format? Will there be any performance issues? If "No" then how can we change the default format of timestamps from datetime to timestamp globally in a laravel application.
For example (default):
$model->created_at = "yyyy-mm-dd h:i-s";
$model->updated_at = "yyyy-mm-dd h:i-s";
Integer timestamp:
$model->created_at = 1523246567;
$model->updated_at = 1523246567;
Unfortunately, I'm not able to answer your first two questions, but Laravel does provide an easy way to change the format your dates are stored in.
The Date Mutators documentation says that one can set the $dateFormat property on your model like this:
/**
* The storage format of the model's date columns.
*
* #var string
*/
protected $dateFormat = 'U';
The 'U' format would be "Seconds since the Unix Epoch." More formats are available in the php date documentation.
You would also need to change your model's migration. Replace $table->timestamps(); with $table->unsignedInteger('created_at'); and $table->unsignedInteger('updated_at');.
To use a specific date format "globally", i.e. for all of your models, you could either set the date format on a base model and let all of your models inherit that model, or use a trait. See this question for an example.

Laravel validate current date against database date using carbon

I'm creating a schedule function where i validate a date field in a table against the current date, if the date is past then i want to update the second column with '3224407' . the field type fecha_vigencia is date.
my schedule function is :
protected function schedule(Schedule $schedule)
{
$schedule->call(function(){
foreach(Equipo::all() as $equipo){
$fecha_vigencia= Carbon::parse($equipo->fecha_vigencia);
if($fecha_vigencia->isPast())
{
DB::table('equipo')->update(['telefono_contacto' => '3224407']);
}
}
}
now my database records before running schedule:run :
image
most of the date fields in the fecha_vigencia column are in the future "2017-08-15",
as displayed on the image above, when i compare against the current date-> "2017-07-31" ,using $fecha_vigencia->isPast(), all fields on the Telephone column are updated. only should update 1 field with date 2017-07-10 instead.
what's wrong with the function?
thanks in advance
You most likely wanted something like this
$equipo->telefono_contacto = '3224407';
$equipo->save();
instead of
DB::table('equipo')->update(['telefono_contacto' => '3224407']);
Right now you're effectively updating the whole table each time $fecha_vigencia->isPast().

Resources