skip to Main Content

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.

2

Answers


  1. 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);
                    };
                })
            ]
        ];
    }
    
    
    
    > Try This 
    
    Login or Signup to reply.
  2. 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);
                })
            ]
        ];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search