0

I'm trying to create a policy like the following:

public function view(User $user, PersonalStatement $personalStatement)
{

    return $user->applicant->id == $personalStatement->applicant_id || $user->mentor->exists();

}

I then test it with a User model where mentor relationship exists, but applicant relationship does not, and I get the error:

Trying to get property 'id' of non-object

I believe this is because the user->applicant returns null in this case.

What's the best way to evaluate if a model has a relationship where the response is either true or false?

Using exists() method returns null if the relationship does not exist.

4

2 回答 2

1

To handle null case, you may use optional Laravel helper, it allows you to call any property/method even if your source is null, it returns null instead of throwing an exception.

public function view(User $user, PersonalStatement $personalStatement)
{

    return optional($user->applicant)->id == $personalStatement->applicant_id || $user->mentor->exists();

}
于 2019-07-22T10:54:12.413 回答
0

To check the 'applicant" relationship of 'User' model, try

$user->applicant()->exists()

OR

$user->applicant()->count()

Note: Brackets after the relationship does really matter.

于 2020-01-05T17:55:16.037 回答