0

I'm struggling with the return code of a validation rule to pass the "Larastan" test.

The code for this rule is:

public function rules(): array
{
    return [
        'name' => [
            'required',
            Rule::unique('domains', 'name')->where(function ($query) {
                return $query->where('organization_id', $this->route('organization')->id);
            })
        ]
    ];
}

And the larastan error is :

 Cannot access property $id on object|string|null.

My question is how to write this rule to be sure it passes the Larastan test ? Of course I could add an "ignoreErrors" in the phpstan.neon file. But I prefer to avoid.

Wahlstrommm
  • 684
  • 2
  • 7
  • 21
Dom
  • 2,984
  • 3
  • 34
  • 64

3 Answers3

0

Try this:

public function rules(): array
{
    return [
        'name' => [
            'required',
            Rule::unique('domains', 'name')->where(function () {
                $organizationId = $this->route('organization')->id;
                return function ($query) use ($organizationId) {
                    return $query->where('organization_id', $organizationId);
                };
            })
        ]
    ];
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

Adding an if statement should fix your static code analysis

public function rules(): array
{
    return [
        'name' => [
            'required',
            Rule::unique('domains', 'name')->where(function ($query) {
                $organization = $this->route('organization');
                if (!$organization || !$organization->id) {
                  throw new \Exception("No organization id ?");
                }
                return $query->where('organization_id', $organization->id);
            })
        ]
    ];
}
Xavier B.
  • 533
  • 2
  • 9
-1

I tried the 2 solutions below. Without success.

I put aside for now. And I opted for an easy solution. I added a line in my phpstan.neon to ignore this error.

ignoreErrors: 
- '#Cannot access property \$[a-zA-Z0-9]#'
Dom
  • 2,984
  • 3
  • 34
  • 64