2

I need to pass a model to a function, but seem that my solution is not correct because i receive below error from PHPStorm

expects parameter of type Illuminate\Database\Eloquent\Model, string given.

this an extract of my code:

 /** Return the model structure
  *
  * @param \Illuminate\Database\Eloquent\Model $model
  * @param array $fillData
  * @return object
  */
public static function fillBasicModelData(Model $model, $fillData){
 ...code...
}

And below is how I call the function:

$result = self::fillBasicModelData(Filter::class, $emptyFilter);

Obviously Filter is an Illuminate\Database\Eloquent\Model

so my question is how can I pass a model to a function without this warning?

thank you

3
  • you should pass a class object, not the class name. Commented Mar 27, 2020 at 9:52
  • Thank you, this can be a good solution or there is a better way? $model = new Filter; $result = self::fillBasicModelData($model, $emptyFilter); Commented Mar 27, 2020 at 9:55
  • try $result = self::fillBasicModelData((new Filter()), $emptyFilter); Commented Mar 27, 2020 at 9:59

1 Answer 1

2

Obviously Filter is an Illuminate\Database\Eloquent\Model

No it isn't. You are passing it with Filter::class. This is the class of the model, not an instance. Basically it translates to the string '\NameSpace\SomeThing\Filter'

Because you are passing the class, and not a model instance, you need it instantiate the model.

public static function fillBasicModelData($model_class, $fillData){
 $model = new $model_class($fillData);
 // ...code...
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, how can I pass the model instead the class? I also try to pass the model with self::fillBasicModelData(Filter, $emptyFilter); but seem not work :(
You need to instantiate the model yourself. $filter = new Filter(); self::fillBasicModelData($filter, $emptyFilter);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.