How to properly type hint custom BaseModel so IDE recognizes child model class instead of BaseModel? #57946
Replies: 1 comment 1 reply
-
So i think one way to properly tell the IDE :is to use the /**
* @template TModel of \App\Models\BaseModel
* @mixin Builder<TModel>
*/
class BaseModel extends Modeldont mind the /**
* @param mixed $id
* @return static|null
*/
public static function find($id, $columns = ['*'])
{
return parent::find($id, $columns);
}now the IDE that you are using knows that you are returning its subclass because in this annotation: now in this annotation /**
*
* @return \Illuminate\Database\Eloquent\Builder<static>
*/
public static function query(): Builder
{
return parent::query();
}now the IDE will know that it returns a Builder specific to the caller or the subclass that is in your case |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a custom
BaseModelthat extendsIlluminate\Database\Eloquent\Model, and I want PHPStorm (and other IDEs) to correctly recognize the return type of Eloquent methods when called on child models.Current issue:
When I write:
$post = Post::query()->first();The IDE thinks
$postis an instance ofBaseModelinstead ofPost.My current code:
And my child model:
Expected:
I want the IDE to recognize that:
Post::query() returns Builder<Post>Post::first() returns Post|nullPost::find($id) returns Post|nulletc.
Beta Was this translation helpful? Give feedback.
All reactions