Retrive all rows from last month (Laravel + Eloquent)

萝らか妹 提交于 2019-12-01 18:34:52

问题


I'm trying to get all records that belongs to last month, so far I managed to get all from last month but to date today, I'm not sure how I can get only for last month

$revenueMonth = Callback::where('created_at', '>=', Carbon::today()->startOfMonth()->subMonth())->sum('payment');

回答1:


More clear solution for your problem:

$revenueMonth = Callback::whereMonth(
    'created_at', '=', Carbon::now()->subMonth()->month
);



回答2:


Try this solutions:

$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString()
);

You get all Callback for last 30 days.

$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->firstOfMonth()->toDateTimeString()
);

Get for current month.

$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->startOfMonth()->subMonth()->toDateString()
);

Get for start last month.

UPDATED

$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->subMonth()->toDateTimeString()
);

This is what are you looking for :)

Hope it will help you:)




回答3:


None of the answers get's me to where I'm looking to go :(.

I have a solution but I think it's ugly and hoped it could be made more clean

$fromDate = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$tillDate = Carbon::now()->subMonth()->endOfMonth()->toDateString();

$revenueLastMonth = Callback::whereBetween(DB::raw('date(created_at)'), [$fromDate, $tillDate])->get();

This will give my the result I'm looking for, here is my records:

2017-09-07 09:46:43
2017-09-07 09:46:43
2017-09-07 09:46:43
2017-09-02 09:46:43
2017-08-07 09:46:43

And I want it to return ONLY what records is made in August 2017 (2017-08-07 09:46:43)




回答4:


UPDATED eloquent version of the your answer

$fromDate = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$tillDate = Carbon::now()->subMonth()->endOfMonth()->toDateString();

$revenueLastMonth = Callback::whereBetween('created_at',[$fromDate,$tillDate])->get();


来源:https://stackoverflow.com/questions/46096260/retrive-all-rows-from-last-month-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!