Insert the current date time using Laravel - php

I want to store the current date time in MySQL using the following Laravel function. Actually, I stored a static date. Instead of this, how can I store the current date time in the created_at and updated_at fields in the database?
function insert(Request $req)
{
$name = $req->input('name');
$address = $req->input('address');
$data = array("name" => $name, "address" => $address, "created_at" => '2017-04-27 10:29:59', "updated_at" => '2017-04-27 10:29:59');
DB::table('student')->insert($data);
echo "Record inserted successfully.<br/>";
return redirect('/');
}

Use the Laravel helper function
now()
Otherwise, use the carbon class:
Carbon\Carbon::now()
It is used like this:
$data = array("name" => $name,"address" => $address,"created_at"=> Carbon::now(),"updated_at"=> now());
DB::table('student')->insert($data);
For more information, see now()

You can also use this to get the current date time. It's working.
$current_date = date('Y-m-d H:i:s');
And also I have updated and set things in your function. You have to add this:
function insert(Request $req)
{
$name = $req->input('name');
$address = $req->input('address');
$current_date_time = date('Y-m-d H:i:s');
$data = array("name" => $name,
"address" => $address,
"created_at" => $current_date_time,
"updated_at" => $current_date_time);
DB::table('student')->insert($data);
echo "Record inserted successfully.<br/>";
return redirect('/');
}

Use this in your database query:
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()

You can use the DateTime object.
Look at the below code:
$curTime = new \DateTime();
$created_at = $curTime->format("Y-m-d H:i:s");
$updateTime = new \DateTime();
$updated_at = $updateTime->format("Y-m-d H:i:s");

Use
use Carbon\Carbon;
at the header of the controller. This code work for Laravel 9:
$updated = Carbon::now();
You may save it inside a variable and use the variable for inserting and updating statements or for any other purpose.
During migration, I defined the column check_at as datetime. And I used the following command for table creation.
php artisan migrate
It generates a timestamp-type column in MySQL. I am passing the variable $updated for update purposes. While using phpMyAdmin, I can see the column check_at has data in date-time format.

Related

php date format does not insert time in database

I am using the date format in my php controller like
$meter->created_at = date('Y-m-d H:i:s');
But the output I am getting is 2017-11-29 00:00:00
I have also checked this solution.
Update 1
I am inserting some data via excel file.
foreach($final_data as $key=>$value)
{
if($key <= $header_index) continue;
$meter = new Meters;
foreach($value as $k=>$v){
$v = preg_replace('/\s+/', ' ', trim($v));
if(isset($fieldSet[0]['meter_msn']) && $fieldSet[0]['meter_msn']==$k){
$meter->meter_msn =$v."";
// echo $v.", ";
}
if(isset($fieldSet[0]['description']) && $fieldSet[0]['description']==$k){
$meter->description = $v;
}
if (isset($fieldSet[0]['status']) && $fieldSet[0]['status'] == $k) {
$meter->status = $v;
}
if (isset($fieldSet[0]['meter_status']) && $fieldSet[0]['meter_status'] == $k) {
$meter->meter_status = $v;
}
if (isset($fieldSet[0]['historic']) && $fieldSet[0]['historic'] == $k) {
$meter->historic = $v;
}
}
$meter->created_at = date('Y-m-d H:i:s');
if($meter->save())
$ok_count++;
else
$status_arr[] = $meter->errors;
}
Any help would be highly appreciated.
Keep the datatype for date fields like created_at and update_at as int and use TimestampBehaviour in your model.
By default, TimestampBehavior will fill the created_at and updated_at attributes with the current timestamp when the associated AR object is being inserted. it will fill the updated_at attribute with the timestamp when the AR object is being updated. The timestamp value is obtained by time() and whenever and where ever you want to show the date you can format it using php's date() function no need to make it complex when the framework itself can do it via conventional approach.
You might have to make little change for renaming the columns to created_at and updated_at and then include the TimestampBehaviour like below in your model.
use yii\behaviors\TimestampBehavior;
public function behaviors() {
return [
TimestampBehavior::className(),
];
}
Or if you want to use the column names as is you can use the following approach to map you field names
use yii\db\Expression;
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'create_time',
'updatedAtAttribute' => 'update_time',
'value' => new Expression('NOW()'),
],
];
}
TimestampBehavior also provides a method named touch() that allows you to assign the current timestamp to the specified attribute(s) and save them to the database. For example,
$model->touch('creation_time');

Laravel - Carbon ->addmonth() giving random dates?

We're having problems creating a webhook service for a payment using "Mollie".
Here's the webhook code
public function premiumPaymentCheck(Request $request)
{
$payment = Mollie::api()->payments()->get(Input::get('id'));
$metadata = $payment->metadata;
$user_id = $metadata->user_id;
if ($payment->isPaid()) {
$user = User::find($user_id);
$user->mollie_customerID = $metadata->customerId;
$user->premium = true;
$user->premium_type = "premium";
$user->subscribed = true;
$user->premium_expire_date = Carbon::now()->addMonth();
$user->save();
}
}
Everything works, except for the premium_expire_date. From what I understand, it should add 1 month from the payment time (the time the payment calls the webhook, so Carbon::now()), but the dates never match.It's always a random date that doesn't really make sense.
Some of the dates are correct, but most of them seem completely of. Any Idea what this might be?
There is no problem with carbon. Check your config/app.php file for timezone property.
'timezone' => env('APP_TIMEZONE', 'UTC'),
Timezone is currently:
'timezone' => 'UTC',
We are in Belgium/Brussels. So should it be:
'timezone' => env('Europe/Brussels', 'UTC')
Alternately it could be:
'timezone' => 'Europe/Brussels',
Thanks for the help!

how to use sql NOW( ) function in laravel

I have used sql's now() function several times in normal query in php db connectivity...
But in laravel it does not displays anything and also the data is not inserted
the code I am using is:
$exercise = Exercise::insert(
array( 'fk_users_id' => '1',
'fk_equipments_id' => $equipment,
'muscular_group' => $muscular,
'exercise_name' => $postedContent['exercise_name'],
'exercise_type' => $postedContent['type'],
'Status' => '1',
'DateCreated' => 'NOW( )',
'DateModified' => 'NOW( )')
);
it stores the data into the database but the time in not stored in any of the columns
at first my method was:
$exerciseDetails = Input::all();
$exercise = Exercise::create($exerciseDetails);
the above method updates date and time itself and worked fine for other controllers but now I am having a problem of having a check box checked array in my post so it throws error
is there any other method in laravel to do this ??
Laravel comes with created_at and updated_at timestamp fields by default, which it keeps updated by itself.
http://laravel.com/docs/4.2/eloquent#timestamps
$now = DB::raw('NOW()');
$now variable can use in insert like
$user = new User;
$user->name = $name;
$user->created_at = $now;
use this
Carbon::now() instead 'NOW( )'
or use DB::raw('NOW()') instead 'NOW()'
You could be looking to direct query to get MySQL DB current Time.
You can go like this;
$currentDBtime = DB::select( 'select NOW() as the_time' );
$currentDBtime[0]->the_time;

Why doesn't this PHP MongoDB query return any results even though there is one?

I have a collection of users and users have a meta.create_date field which is an ISODate as seen below. I am trying to count how many users were created in the last N days. I have the following in the database:
{
"_id" : ObjectId("51e61fa16803fa40130a0581"),
"meta" : {
"create_date" : ISODate("2013-07-17T04:37:53.355Z")
}
}
My PHP code:
$daysAgo = new MongoDate(date('c', strtotime('-7 days')));
$query = array(
'meta.create_date' => array(
'$gte' => $daysAgo,
)
);
$result = $this->db->users->count($query);
I have also tried specifying a range using '$gte' and '$lte' where $lte => today.
However, result is coming back as 0. So what is going on here?
MongoDate() takes int time(). So, passing in a php date() to the constructor does not work. This is the proper way:
$daysAgo = new MongoDate(strtotime('-7 days'));

How to set current date and time in table field using zend

I am having table called users with following fields ,
is_login(tinyint(1)) and last_login(datetime).
Below is the piece of code to update when user is online using Zend,
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1,'last_login'=>$currentDateTime);
$this->_db->update( 'users', $data,'id = '.$id);
}
Here i am using $currentDateTime = date('Y-m-d H:i:s'); to store current data and time. But it seems not ok with time.
Kindly suggest me the best way to store current data and time using Zend .
Thanks in Advance,
Dinesh Kumar Manoharan
I'm not exactly sure what's causing your problem, but I find using NOW() to be easier. Also, you should ensure the variable $id gets quoted in the update's where condition.
public function updateLastLoginDetails($id){
$data = array('is_online' => 1, 'last_login' => new Zend_Db_Expr('NOW()'));
$this->_db->update('users', $data, array('id = ?' => $id));
}
It looks like you forgot to use $data anywhere in your code!
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1, 'last_login'=>$currentDateTime);
$this->_db->update('users', $data, 'id = '. (int)$id);
}
You might want to consider using a TIMESTAMP field in place of a DATETIME for last_login and have MySQL update it automagically.
Hi am I understanding correctly that the year month and day are being inserted correctly but not the hour minutes and seconds? If that is the case can you please provide use with a describe of the users table. Just execute "DESCRIBE users" in phpMyAdmin.
If that is the case it could be that the field is of type DATE and not DATETIME.

Categories