Column not found: 1054 Unknown column 'MONTH(date)' in 'where clause'

Viewed 416

i dont see what's my problem here, im just trying to get the month and the year from a date column in my DB, i was already using this query and it was working and now its not i really dont understand. ( new to laravel)

heres my controller:

public function showMonth($month, $year)
    {
        $workers = WorkerSalarie::all();

        $worker = WorkerSalarie::select('*')
        ->where('MONTH(date)','=',$month)
        ->where('YEAR(date)','=',$year)
        ->get();

        return view('backoffice.dashboard.show', compact('month', 'year', 'workerss'));

    }

and this is the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'MONTH(date)' in 'where clause' 
(SQL: select * from `worker_salaries` where `MONTH(date)` = 3 and 
`YEAR(date)` = 2021)
1 Answers

As shown here.

Since Laravel prepares the querys before excuting them, you can use the whereMonth and whereYear methods to tell Laravel to not escape your clauses:

Change this:

->where('MONTH(date)','=',$month)
->where('YEAR(date)','=',$year)

For this:

->whereMonth('date', '=', $month])
->whereYear('date', '=', $year)

Check the docs for this methods here.

Other (less clean) option would be to use the whereRaw method.

Related