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 badges1 Answer
Reset to default 1If 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744650796a4585886.html
评论列表(0条)