laravel current timestamp in migration with carbon - laravel

I want to display created_at as a timestamp like this :
created_at : 1625501162
so this is my created_at column in migration:
$table->string('created_at')->Carbon::now()->timestamp;
Now I want this field to be created automatically when a new record is created and record the current time. so when i change the line to this :
$table->string('created_at')->useCurrent(Carbon::now()->timestamp);
gives me this error :
Method call is provided 1 parameters, but the method signature uses 0 parameters
so how can i fix this problem?
What other ways do you suggest for timestamp created_at and store it automatically?

If you want your column to be a timestamp you should use timestamp() instead of string(). useCurrent() doesn't take a parameter. Change
$table->string('created_at')->useCurrent(Carbon::now()->timestamp);
to
$table->timestamp('created_at')->useCurrent();
https://laravel.com/docs/8.x/migrations#column-method-timestamp
https://laravel.com/docs/8.x/migrations#column-modifiers
Edit: to always get a timestamp instead of a date you can use
protected $casts = ['created_at' => 'timestamp'];
in your Model.

Instead of string you may use timestamp() in your migration.
$table->timestamp('created_at')->useCurrent();
Also you may use casting inside model to always get expected format when receiving model.
class Something extends Model {
protected $cast = [
'created_at' => 'timestamp'
];
}

A simpler way is to configure the date format of the model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The storage format of the model's date columns.
*
* #var string
*/
protected $dateFormat = 'U';
}
No need to put a default value in the migration. everytime created_at, updated_at and deleted_at(if you use soft delete) is to be updated/filled, it will be in a unix timestamp format
Migration should be an integer
$table->integer('created_at')->nullable(); //you can omit this nullable
$table->integer('updated_at')->nullable(); //you can omit this nullable
// if you use softDelete trait
$table->integer('deleted_at')->nullable();

This is an example of a column createdAt. When a new record is created, it defaults to the date in UNIX format.
$table->integer('createdAt')->default(DB::raw('extract(epoch from now())'));

Related

Laravel Set Model Table Name With Todays Date

I have a model in my laravel appication which uses a table which is re-created each day with a new table name that includes todays date.
I am trying to set the protected $table property in the model to
protected $table = "probe_request_" . $this->getDate;
This is how I have defined the getDate function
private function getDate()
{
return Carbon::now('Europe/London')->startOfDay()->format('d_m_Y');
}
I keep receiving the following error "<strong>Zend compile error</strong>: Constant expression contains invalid operations in <strong>/var/www/intelli_sense/app/sprinkles/geo-sense/src/Database/Models/ProbeRequest.php</strong> on line <strong>23</strong>"
Is there a way I can set the table name with todays date in it? I feel like there must be an easy way to do this that I have missed.
You can't use expressions while creating a field value, but you can override it inside the model constructor:
public function __construct(array $attributes = [])
{
$this->table = "probe_request_" . Carbon::now('Europe/London')->startOfDay()->format('d_m_Y');
parent::__construct($attributes);
}
You can set the new table name like this.
$ProbeRequest= new ProbeRequest;
$ProbeRequest->setTable("probe_request_" . $this->getDate);

Adding two created_at on one insert

I want to add another created_at column on the database columns for reference.
I want to have a created_at and created_at1 at the same time.
This is what I have in my Model:
const CREATED_AT = 'created_at1';
protected $dates = [created_at, created_at1];
But I'm receiving this error: Field 'created_at' doesn't have a default value.
You do not need to add casting to the created_at since Laravel has already done it for you.
You need to add inside the string like
protected $dates = ['created_at1']
If you want to set the created_at1 when a new model is created, you can add Model Events.
Inside your model,
protected static function boot(){
parent::boot();
static::creating(function($model){
$model->created_at1 = Carbon::now();
});
}
Inside controller
$model = Model::create([
...
]);
Now it will set created_at and created_at1
For the insert, you have to manually save the value to the created_at1 because it will not reflect the model event.
Model::insert([
...
'created_at1' => Carbon::now()
]);
You might not be passing value to created_at column while inserting data. Please do check. If this is not the case please do provide more information on your problem.

Why is Laravel eloquent returning empty

This is my model
namespace App\Models\Invitation;
use App\Models\Model;
class SendtoType extends Model
{
}
When i get data from SendtoType it return empty or null but i sure sendto_types table has datas
$types = SendtoType::all();
dd($types); // return empty collection
$types = SendtoType::find(1);
dd($types);// null
It's happend after i run php artisan command:reset_table sendto_types command.
I cleared cache but it's not working.
Thank you everyone, i found my mistake:
i set timestamp for table's deleted_at column but forgot to set not null so it also filled deleted_at column when i add data.
That's why eloquent clause return empty.
So silly mistake!
You can add protected $table = 'sendto_types'; inside your model class with actual table name in your database.
class SendtoType extends Model
{
protected $table = 'sendto_types';
}
Command command:reset_table is not a built in command, so you'd need to look at your source code to see what it does, but by the name of it, I would assume the command empties your table.
In this case, your table is empty, so your query will not return any results.

How does laravel/lumen dateformat 'U' actually works?

I'm not able get the timestamps with dateformat 'U' working in lumen.
In migration:
$table->timestamps();
In Model:
protected $dateFormat = 'U';
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
public function getDateFormat()
{
return 'U';
}
Insert row from controller:
$model = new ApiKey;
$model->random= rand();
$model->name = $name;
$model->scope = $scope;
$model->save();
It does insert the row in the database but with 0000-00-00 00:00:00 values for created_at and updated_at columns.
Also, while retrieving a model via toArray or toJson it thrown exception:
I want lumen to autoupdate the timestamps and retrive timestamps as unixtimestamp format i.e. number of seconds from 1st Jan 1970.
Also, $table->timestamps() didn't create deleted_at column. What do I need to do get this column created via laravel.
Is there any other option than $table->timestamp('deleted_at');?
I've found a solution bay changing timestamps columns to int. But I want the things to be done in laravel way.
Unix timestamps are integers, not compatible with SQL datetime/timestamp fields. If you want to use unix timestamps, use integer field types for storage.
The timestamps() method only creates created_at and updated_at, soft deletes are not enabled by default. This method should not be used if you want integer storage.
If you only want to change the output format when serializing data, use casting:
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime:U',
];
This is likely caused by the fact that Laravel/Lumen created the date/time columns as the type timestamp not int so you're trying to save wrong type of data in the field, causing the 0000-00-00 00:00:00.
This would also cause the carbon issue as you are trying to createFromFormat with the wrong format compared to the content.
You can use $table->integer('deleted_at'); in your migration to create a deleted_at column.
TL;DR:
Manually create your date time columns with $table->integer('updated_at').
<?php
namespace App\Traits;
use Illuminate\Support\Carbon;
trait sqlServerDateFormat
{
public function fromDateTime($value)
{
return Carbon::parse(parent::fromDateTime($value))->format('d-m-Y H:i:s');
}
}

Eloquent set updated_at value with creating. Ho can fix it?

In Eloquent when instantiating the model established by the two timestamps - created_at and updated_at with the same values. But according to the logic when you create a label should be established whether the created and the label is updated the next time you upgrade. How to fix it?
Eloquent 5.2, created_at and updated_at in db is integer (protected $dateFormat = 'U')
UPDATE - when I use the method, the properties created_at and updated_at is still updated at the same time. That is the first action - the creation, are set equal. The second action - update. Again, both fields are updated and they have the same value.
This is how Laravel does things sometimes, not letting the updated_at null is also a way to avoid problems with not null constraints. But you can fix that for you, if you please. You probably will be able to do something like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
class BaseModel extends Eloquent
{
public function save(array $options = [])
{
$saved = parent::save($options);
if ($this->wasRecentlyCreated) {
$this->updated_at = null;
parent::save($options);
}
return $saved;
}
}
And use this BaseModel in all your models

Resources