3

I'm trying to fetch the first result from my data where the date is equal to last months date range.

This is can example of my database contents -

id  date_recorded
1   2016-07-22 15:21:33
2   2016-08-13 12:22:22
3   2016-07-06 12:22:22
4   2016-09-12 12:45:22

This is my query to fetch the 2nd result (the most recent from the last month).

$seoScoreLastMonth = Manual::where('account_id', Auth::user()->account)
->where('date_recorded', '>=', Carbon::now()->subMonth())
->orderBy('date_recorded', 'desc')
->pluck('seo_score')
->first();

The result returned is null, this is because the first result in the database by id does not match the date?

Machavity
  • 30,841
  • 27
  • 92
  • 100
archvist
  • 712
  • 2
  • 18
  • 41
  • Just to make sure, does your first where-statement match any information? – Chris Forrence Sep 13 '16 at 16:12
  • Yes, I've tried a number of combinations and it all works and I can dump the results in the correct order. It's only when I say where the date->subMonth which just seems to throw it and return the first value – archvist Sep 13 '16 at 16:16
  • Alright, and which version of Laravel are you using? I ask because I'm entering `App\Models\User::where('created_at', '>=', Carbon\Carbon::now()->subMonth())->orderBy('created_at')->pluck('first_name')->first();` in a local Laravel 5.3 app and it returns data. – Chris Forrence Sep 13 '16 at 16:20
  • Try using Carbon\Carbon::now()->subMonth()->toDateTimeString() instead of Carbon\Carbon::now()->subMonth() – Julian Rodriguez Sep 13 '16 at 16:23
  • Another question: does the `seo_score` field exist in the manuals table? When I tried to pluck a non-existant field, it returned null. – Chris Forrence Sep 13 '16 at 16:24
  • Hi yes, the field does have the seo_score, I'm able to run the following query using an orderBy but not a where statement - ```$seoScoreLastMonth = Manual::orderBy('date_recorded', '>=', Carbon::now()->subMonth())->get();``` – archvist Sep 14 '16 at 08:09

1 Answers1

1

I needed this month. Here is my query. I think You'll be able to modify it if you need

$start = new Carbon('first day of this month');
$start = $start->startOfMonth()->format('Y-m-d H:i:s'); // startOfMonth for 00:00 time

Your query..->where('date_recorded','>',$start)..

With help of Carbon - get first day of month enter link description here

Vit
  • 396
  • 2
  • 7
  • 16