skip to Main Content

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?

3

Answers


  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

    Login or Signup to reply.
  2. 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).

    Login or Signup to reply.
  3. If your Date column is type of date, please try like that

    Query1::where('Course_ID', '=', $request->FLA)->where('Date', '=', Carbon::now()->toDateTimeString());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search