1

How would you go about inserting a php variable $date into an eloquent whereRaw? The following will work with curDate() but can't pass a variable through.

$ex = User::whereRaw('month({$date}) = month(dob) and day($date) = day(dob)')->get();
T Warren
  • 13
  • 1
  • 5

2 Answers2

4

I don't know whether the value of date will decided by user or php script but you always have to prepare raw statement by PDO,

Your raw statement will look like (safe)

$ex = User::whereRaw('month(?) = month(dob) and day(?) = day(dob)')->setBindings([$date, $date])->get();

Or

$ex = User::whereRaw("month($date) = month(dob) and day($date) = day(dob)")->get();

Also you have to look into this answer, PHP - concatenate or directly insert variables in string

Chintan7027
  • 7,115
  • 8
  • 36
  • 50
0

You may try by replacing ' with "

$ex = User::whereRaw("month({$date}) = month(dob) and day($date) = day(dob)")->get();
Mahbub
  • 4,812
  • 1
  • 31
  • 34
  • No luck, possible '$date' is in the wrong format? It's coming through from an AJAX request to the controller, outputting to the log give a date in the format '2017-06-29', but does not seem to work when inserting the variable into the raw sql, though copying and pasting the value directly into the sql '$bu = User::whereRaw("month('2017-06-29') = month(dob) and day('2017-06-29') = day(dob)")->get();' does work – T Warren Jul 02 '17 at 07:38