1

I have this code to get events which is in current year:

$year = "YEAR('".date('Y/m/d')."')";
$event = Event::where('date_start', $year);
var_dump($event->toSql());

But the query representation of the code is as follows:

"select * from `events` where `date_start` = ? and `events`.`deleted_at` is null"

Why is that? Where my mistake?

6
  • now whats wrong with this query? the question mark? Commented Jul 15, 2017 at 14:48
  • What is wrong with the query? Note that this is a prepared statement. The placeholder ? will be "replaced" with $year when you execute the query. Commented Jul 15, 2017 at 14:49
  • with that code above, the result is null event if the condition is true Commented Jul 15, 2017 at 14:51
  • 1
    What is the data type of date_start? Commented Jul 15, 2017 at 14:53
  • 1
    Code issues aside, the query won't produce the desired results unless date_start only contains the year. Also, why the convoluted way to get the year? YEAR('".date('Y/m/d')."')" could simply be date('Y') Commented Jul 15, 2017 at 14:53

1 Answer 1

3

If you want to get the records with specific year in a datetime type field of MySQL, you can use Eloquent's whereYear():

$year = 2017;
$event = Event::whereYear('date_start', '=', $year)->get();

Or obviously $year = date("Y") if you want events from current year!

Sign up to request clarification or add additional context in comments.

1 Comment

Another way could be whereRaw('year(date_start) = year(now())').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.