Reputation: 137
$rankArray = [
'ranks' => $product[0]['productSalesRank']->pluck('rank'),
'dates' => $product[0]['productSalesRank']->pluck('created_at')
];
$rankArray['dates']->transform(function ($item) {
return $item->format('d-m-Y');
});
Having to transform everytime I retrieve the created_at/updated_at date from the database seems so inefficient, is there a simplier way of doing this?
I want to keep the date as Carbon, but in some instances, do just want the "value"
Upvotes: 2
Views: 3442
Reputation: 1323
Set a getter in your productSalesRank's Model(?) that does all the work for readying your dates.
Model:
class ProductSalesRank extends Model
{
protected $dates = ['created_at', 'updated_at'];
// whatever other columns you want to use Carbon on ^.
public function getCreatedAtHumanAttribute() {
return $this->created_at->format('d-m-Y');
}
}
View/Controller/Wherever:
$productSalesRank->created_at_human; // will print it like you defined it in the model.
Why _human?
Sometimes later in the code you will find yourself needing the Carbon features on the created_at value. When you use format(), it returns a string, stripped out of Carbon features.
[Update]
Earlier we created a getter/accessor. As far as I know, you can't pass a variable like:
->created_at_human('mm')
because it isn't a method, it is an accessor.
In your Model, create a function.
public function myFunction($format) {
return $this->created_at->format($format);
}
In your view, simple:
$productSalesRank->myFunction('d-m-Y');
Upvotes: 3
Reputation: 611
In your table related model,
class ModelName{
//add this line
protected $dates = ['created_at','updated_at'];
}
Defining$dates
in model will automatically give you the carbon instances of dates.
Upvotes: 0
Reputation: 201
You can add an accessor to your model, that automatically converts the data to the desired format. More about: https://laravel.com/docs/5.2/eloquent-mutators#accessors-and-mutators
Upvotes: 0