I am trying to figure out a way where I can check if my record in database was created in a different year by using the created_at column. The condition is like this. If I bought a phone this year which is 2022, then I can only purchase a new phone in the next year which is 2023. If possible, I want the result to be in boolean because Im going to use it inside an if else condition.I hope my explanation is clear.
CodePudding user response:
whereYear()
whereYear() will help to get only specific year records from your timestamps fields. you can see bellow example.
$products = DB::table('products')
->whereYear('created_at', '2016')
->get();
dd($products);
CodePudding user response:
You can explore using Carbon, which I believe is used in Laravel as well.
An example here (you should customise to your need):
use Carbon\Carbon;
$phoneRecord = Model::query()->find(...);
$phoneBuyDate = Carbon::createFromFormat('Y-m-d H:i:s', $phoneRecord->created_at);
$canBuyPhone = $phoneBuyDate->copy()->addYear(1)->isSameYear(Carbon::now());
More details here: https://carbon.nesbot.com/docs/