0

I am trying to get time availability for my scheduling system. I know how to do it with plain SQL query but I am having trouble translating the query to Laravel Eloquent. My query is like the one below

$query =  "SELECT * FROM schedules WHERE (time_start BETWEEN '$start_datetime' AND '$end_datetime') OR (time_endBETWEEN '$start_datetime' AND '$end_datetime')";

and here's what I have tried with laravel eloquent so far

$sch = DB::table('schedules')
                ->where(function ($query) {
                    $query->whereBetween('time_start', [$start_datetime, $end_datetime]);
                })
                ->orWhere(function($query){
                    $query->whereBetween('time_end', [$start_datetime, $end_datetime]);
                })->get();

any ideas how to do it right? I am getting an error with my laravel eloquent query Undefined variable: start_datetime

Thanks

Kim Carlo
  • 1,173
  • 3
  • 19
  • 47

1 Answers1

1

You need to call the variables to closure scope by using use

$sch = DB::table('schedules')
                ->where(function ($query) use ( $start_datetime,$end_datetime) {
                    $query->whereBetween('time_start', [$start_datetime, $end_datetime]);
                })
                ->orWhere(function($query) use ( $start_datetime,$end_datetime){
                    $query->whereBetween('time_end', [$start_datetime, $end_datetime]);
                })->get();
Suresh Velusamy
  • 2,338
  • 19
  • 24
  • thanks for this. but I am not getting any results from the database. it returns a blank collection. I also tried changing the values of `$start_datetime` and `end_datetime` variables to make a match on the database but still no results. – Kim Carlo Sep 16 '17 at 09:53
  • then something wrong in your query, You may enable query log and compare your query then can resolve https://stackoverflow.com/questions/18236294/how-do-i-get-the-query-builder-to-output-its-raw-sql-query-as-a-string – Suresh Velusamy Sep 16 '17 at 09:57
  • found it, I'm passing wrong values to the variables that's why it isn't working.. now I am getting results. Thanks mate! – Kim Carlo Sep 16 '17 at 10:08