Yii2 filter data in controller

I’m new to YII framework, I want to filter my data on the frontend using product, month and year dropdown. Here is what I have in my controller

public function actionProducts()
        $sql = "SELECT product, cost, supplier, month, year 
                FROM products
                WHERE year = :year
                GROUP BY product, month, year";
        $product = Data::findBySql($sql, [':year' => 2018])->asArray()->all();

        $response = ['data' => $product];
        header('Content-Type: application/json');
        return json_encode($response, JSON_NUMERIC_CHECK);

How do I approach this?

First make use of yii\rest\Controller class. It does a lot for you. See Restful services. That being said, here is how


use yii\data\ActiveDataProvider;

class ProductsController extends \yii\rest\Controller
    public function actionProducts($product = null, $month = null, $year = null)
        $query = Product::find()->filterWhere(['month' => $month, 'product' => $product, 'year' => $year]);

        return new ActiveDataProvider([
            'query' => $query,
            //sert others like sorting and pagination

Make sure front end passes whatever filter as query param in this case


Take enough time for you to read through the guide. It’s worth doing.
Make haste slowly.