BelongsToMany relationship are not loaded in policy, but works fine on test. How to fix this? #35329
-
I want to authorize
class FieldReportPolicy
{
use HandlesAuthorization;
...
/**
* Determine whether the user can view the model.
*
* @param \App\Models\User $user
* @param \App\Models\FieldReport $fieldReport
* @return mixed
*/
public function view(User $user, FieldReport $fieldReport)
{
dd($fieldReport->taggedUsers);
return $user->can('view fieldReport')
&& $fieldReport->taggedUsers->contains(['id' => $user->id])
|| $user->id === $fieldReport->user_id
|| $user->getRoleNames()->contains('customer');
}
...
}
Meanwhile in my test, when I
class FieldReportTest extends TestCase
{
...
public function testShowShouldBeAccessibleByEmployeeThatAreTagged()
{
$company = Company::factory()->createOne([
'user_id' => $this->user->id,
]);
$branch = Branch::factory()->createOne([
'user_id' => $company->user_id,
'company_id' => $company->id
]);
$someone = User::factory()->createOne([
'company_id' => $company->id,
'branch_id' => $branch->id,
]);
$someonesReport = FieldReport::factory()->createOne([
'user_id' => $someone->id,
'company_id' => $company->id,
'branch_id' => $branch->id,
]);
$someonesReport->taggedUsers()->attach($this->user->id);
// Here...
dd($someonesReport->taggedUsers);
$this->actingAs($this->user->assignRole('employee'), 'api')
->getJson(route('fieldReports.show', $someonesReport))
->assertOk()
->assertJsonFragment($someonesReport->toArray());
}
...
}
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I found the problem as well as the answer for this question. It was my mistake The reason why I got 403 was here: $fieldReport->taggedUsers->contains(['id' => $user->id]); I was awfully trying to check the existence of both key and value when the I simply changed to this and it passes: $fieldReport->taggedUsers->contains($user->id) Everything works as expected now. All tests passes. |
Beta Was this translation helpful? Give feedback.
I found the problem as well as the answer for this question. It was my mistake
dd
-ing on thePolicy
class. The test was dumped early even before it touches my targetted test case, the rest of the test were blocked because the app gotdie
-ed, the attach method on my test case are not even get called. This is why I got an empty array.The reason why I got 403 was here:
I was awfully trying to check the existence of both key and value when the
taggedUsers
are already an array containing that key. Thecontains
method are meant to be used to check an existence of value given in an array, not the entire key value pair.I simply changed t…