Setting unknown property: yii\rest\ViewAction::prepareDataProvider


I’m trying to expand a relationship by default, without having to add the expand querystring parameter.

From what I understand, I need to use the action’s “prepareDataProvider” property, which is what the docs says ( So here is what I tried in my Rest controller:

public function actions()
    $actions = parent::actions();
    $actions['view']['prepareDataProvider'] = [self::class, 'prepareDataProvider'];
    return $actions;
public function prepareDataProvider()
    $query = User::find()->with('company');
    return new ActiveDataProvider([ 
        'query' => $query,

What am I doing wrong to get the error?
Setting unknown property: yii\rest\ViewAction::prepareDataProvider

I guess you are not using yii\rest\ActiveController but yii\rest\Controller. ActiveController defines actions you can extend like in your example. If you don’t want to use ActiveController just copy it’s actions() method and work from that point.

Edit —

Sorry, my bad, you are using proper controller but you are using prepareDataProvider wrong. It’s not in ViewAction (which is for single resource only). It’s for IndexAction.

Thanks for your answer, just found the notification in my spam folder.

So, yes, I’m using the proper ActiveController as you mentionned. What I was trying to accomplish is to change the dataProvider for the viewAction, so for a single resource. Still haven’t found a way to accomplish that though.

There is no data provider for ViewAction since it’s handling a single resource.

Ok… I might be trying to do this the wrong way then.

Real-life example. I want to return a post only if it was published in the category my connected user is part of? How can I modify the query the api uses for the viewAction to add that constraint to the query?

Edit: I could create my own viewAction class and update the actions() array to load mine. I guess that makes sense!

Yes, you can create your own. Also you can use findModel:

$actions['view']['findModel'] = static function ($id, Action $action) {
    $modelClass = $action->modelClass;
    $model = $modelClass::findOne(/* what you need */);
    if ($model === null) {
        throw new NotFoundHttpException("Object not found: $id");
    return $model;

Oh thanks a lot! Really appreciated.

I’m not new to Yii, I used it with Craft CMS for a while, but I’m new starting an application with it myself. It’s in these time you can appreciate the work that was put into the full app on top of Yii!