Anton Flärd
Anton Flärd

Reputation: 313

Laravel Model protected $dateFormat - How to remove seconds?

Platform: Laravel 5.1

Database: MySQL

I'm also using Fractal Transformers for transforming my returned data to JSON objects.

After putting this protected $dateFormat = 'Y-m-d H:i'; in my Model(note the missing :s) Carbon is throwing errors:

exception 'InvalidArgumentException' with message 'Trailing data' in C:\project1\vendor\nesbot\carbon\src\Carbon\Carbon.php:425

According to the documentation this should work: https://laravel.com/docs/5.1/eloquent-mutators#date-mutators

I've tried the following:

I might be using a different Persistence that doesn't use the MySQL format

What does this mean?

How do I make sure Carbon::now() or MySQL is creating timestamps without seconds?

OR

How do I return only Y-m-d H:i?

Upvotes: 3

Views: 5931

Answers (2)

Abdelsalam Megahed
Abdelsalam Megahed

Reputation: 1501

With the help of Accessor & mutators you can format the timestamp as you would like to.

Here's an example of created_at timestamp:

`public function getCreatedAtAttribute($value)
 { 
      return $this->asDateTime($value)->format('Y-m-d H:i'); 
 }`

Here's an example of updated_at timestamp with a little bit different format:

`public function getUpdatedAtAttribute($value)
 {
     return $this->asDateTime($value)->format('d/m/Y - H:i');
 }`

Upvotes: 2

Someshwer Bandapally
Someshwer Bandapally

Reputation: 149

You can try the following

Place the following code on your model

 protected $casts = ['date_time'=>'date'];

For carbon use the following

 Carbon::now()->format('Y-m-d H:i');

Upvotes: 1

Related Questions