-2

I am trying to make a query using Eloquent Model in Laravel.

My original query does not work

Query1::where('Course_ID', '=', $request->FLA)
->where('Date', '=', Carbon::today())

I would like the query to include both inside of a single WHERE, akin to:

Query1::where('Course_ID', '=', $request->FLA && 'Date', '=', Carbon::today())

Is this possible?

John Lyons
  • 11
  • 4
  • 3
    They would be functionally equivalent regardless of how you write it, chaining where conditions adds an AND in SQL. Try debugging, see this answer for viewing the raw SQL: https://stackoverflow.com/a/76600346/1583522 – Devon Bessemer Aug 03 '23 at 17:22

3 Answers3

1

You can use:

Query1::where([
   'Course_ID' => $request->FLA,
   'Date' => Carbon::today()
]);

It will create the following SQL query:

SELECT * FROM tablename WHERE Course_ID = ? AND Date = ?

But your approach, using two 'where's will have the same output

William Martins
  • 357
  • 2
  • 14
0

The way you have your query written, using ->where()->where() will generate the following query:

SELECT * FROM query_1 WHERE Course_ID = ? AND Date = ?

If you want your WHERE clause to be "scoped", you can use this syntax:

Query1::where(function ($subQuery) use ($request) {
  return $subQuery->where('Course_ID', '=', $request->FLA)
  ->where('Date', '=', Carbon::today());
})->get();

This will generate the query:

SELECT * FROM query_1 WHERE (Course_ID = ? AND Date = ?)

Notice the () around Course_ID = ? AND Date = ?

This is useful when you want to add conditions that need to be grouped, i.e. if you were adding another WHERE that could conflict with the existing one(s).

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
0

If your Date column is type of date, please try like that

Query1::where('Course_ID', '=', $request->FLA)->where('Date', '=', Carbon::now()->toDateTimeString());
Ahmet Firat Keler
  • 2,603
  • 2
  • 11
  • 22