Using day, Month or Year as MYSQL query filter in Laravel

时间:2019-04-08 13:28:49

标签: laravel

In my code, i am querying a database by accepting month and year input from user.

I have tried writing it the normal PHP way and other ways i can find online but none seems to be working. here is the code i am using currently

$salesmonth = $request->input('mn');
$salesyear = $request->input('yr');
$id = Auth::user()->id;
$comm = \DB::table('bakerysales')
    ->where([
        ['customer_id', '=', $id], [MONTH('sales_date'), '=', $salesmonth], [YEAR('sales_date
'), '=', $salesyear]
    ])
    ->get();

return view::make('showCommission')->with('comm', $comm);

I expect the query to return data from rows that match user selected month and year

1 个答案:

答案 0 :(得分:2)

Laravel comes with a few different where clauses for dealing with dates e.g.
whereDate / whereMonth / whereDay / whereYear.

This means that your controller method can look something like:

$comm = \DB::table('bakerysales')
    ->where('customer_id', auth()->id())
    ->whereMonth('sales_date', $request->input('mn'))
    ->whereYear('sales_date', $request->input('yr'))
    ->get();

return view('showCommission', compact('comm'));