admin管理员组

文章数量:1389836

I have a method that performs a find() and return the model, like this:

function getRecord(string $id): MyModel
{
  return MyModel::query()->findOrFail($id);
}

With this code I get the following error when using Larastan v2 at level 7:

  53     Method                                                               
         App\Actions\MyModelAction\MyAction::getRecord()    
         should return App\Models\MyModel but returns                     
         App\Models\MyModel|Illuminate\Database\Eloquent\Collection<int,  
         App\Models\MyModel>.  

The only way i found to solve this problem is to introduce a variable, like this:

function getRecord(string $id): MyModel
{
  /** @var MyModel $result */
  $result = MyModel::query()->findOrFail($id);
  return $result;
}

There is a way to prevent a variable definition, and using directly the return and make larastan happy at level 7?

This is just an example, in this case a method like this is an overkill, but in more complex scenarios we need to use a function to perform some actions and at the end return a query like in this example.

I have a method that performs a find() and return the model, like this:

function getRecord(string $id): MyModel
{
  return MyModel::query()->findOrFail($id);
}

With this code I get the following error when using Larastan v2 at level 7:

  53     Method                                                               
         App\Actions\MyModelAction\MyAction::getRecord()    
         should return App\Models\MyModel but returns                     
         App\Models\MyModel|Illuminate\Database\Eloquent\Collection<int,  
         App\Models\MyModel>.  

The only way i found to solve this problem is to introduce a variable, like this:

function getRecord(string $id): MyModel
{
  /** @var MyModel $result */
  $result = MyModel::query()->findOrFail($id);
  return $result;
}

There is a way to prevent a variable definition, and using directly the return and make larastan happy at level 7?

This is just an example, in this case a method like this is an overkill, but in more complex scenarios we need to use a function to perform some actions and at the end return a query like in this example.

Share asked Mar 14 at 14:31 Mistre83Mistre83 2,8276 gold badges46 silver badges83 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

If you look inside of the find() and findOrFail() methods you can see that they both return either a single Model or a Collection if the searched id is an array.

If you want to ensure that you're going to return a single model only you can use first() or firstOrFail().

Also i've tried your function on a Laravel 11 project with Larastan level 7 and i didn't get any error, maybe try to update your larastan version ? Mine was 2.9.13.

本文标签: laravelLarastan v2wrong return type using findStack Overflow