Laravel Case Study: Make an Accessor Calculate The Age of an Item with Month and Day in Laravel
Case: In the warehouse application, display how long an item or items have been in the warehouse.
model Stock.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Carbon\Carbon;
class Stock extends Model
{
use HasFactory;
protected $fillable = [
'warehouse_id',
'product_id',
'quantity',
'remaining_quantity',
'currency',
'price',
'receive_product_id',
];
public function age(): Attribute
{
$days = Carbon::parse($this->created_at)->diff(Carbon::now())->days;
$month = intval($days / 30);
$day = $days - ($month * 30);
return Attribute::make(
get: fn () => '<strong>'.$month.'</strong>'. ($month > 0 ? ' months ': ' month ').'<strong>'.$day.'</strong>'. ($day > 0 ? ' days' : ' day'),
);
}
}
In the code snippet above, I created an accessor function called age which will return the Attribute. This means that age will be an additional attribute in the Stock model. How do I get the number of months and days from the created_at attribute?
Steps:
- I use carbon to get the number of days. How it works is by using the diff feature to find out the time difference between today's time now() and the time of created_at
$days = Carbon::parse($this->created_at)->diff(Carbon::now())->days;
- Then to get the month, I divide the number of days that have been obtained by 30 days.
The result of the division can be decimal, the number in front is the month, while the last number is the day. I use intval to round the number, from that I get the month number.intval($days / 30);
- Meanwhile, to get the remaining days, I subtract the number of all days by the month times the days.
$day = $days - ($month * 30);
- Finally, in the get method of the accessor function, I compose the text that will be used later.
{!! $stock->age !!};
And this is the result: