Skip to content

Commit 4f7ee1d

Browse files
authored
[9.x] Fix whenPivotLoaded(As) api resource methods when using Eloquent strict mode (#44792)
* Add failing test * Use isset method * Fix linting
1 parent 05f7a7c commit 4f7ee1d

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ protected function whenPivotLoadedAs($accessor, $table, $value, $default = null)
291291
}
292292

293293
return $this->when(
294-
$this->resource->$accessor &&
294+
isset($this->resource->$accessor) &&
295295
($this->resource->$accessor instanceof $table ||
296296
$this->resource->$accessor->getTable() === $table),
297297
...[$value, $default]

tests/Integration/Http/ResourceTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Tests\Integration\Http;
44

5+
use Illuminate\Database\Eloquent\Model;
56
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
67
use Illuminate\Http\Exceptions\PostTooLargeException;
78
use Illuminate\Http\Request;
@@ -443,6 +444,33 @@ public function testResourcesMayHaveOptionalPivotRelationships()
443444
]);
444445
}
445446

447+
public function testResourceDoesNotThrowErrorWhenUsingEloquentStrictModeAndCheckingOptionalPivotRelationship()
448+
{
449+
Model::shouldBeStrict(true);
450+
451+
Route::get('/', function () {
452+
$post = new Post(['id' => 5]);
453+
(function () {
454+
$this->exists = true;
455+
$this->wasRecentlyCreated = false;
456+
})->bindTo($post)();
457+
458+
return new PostResourceWithOptionalPivotRelationship($post);
459+
});
460+
461+
$response = $this->withoutExceptionHandling()->get(
462+
'/', ['Accept' => 'application/json']
463+
);
464+
465+
$response->assertStatus(200);
466+
467+
$response->assertExactJson([
468+
'data' => [
469+
'id' => 5,
470+
],
471+
]);
472+
}
473+
446474
public function testResourcesMayHaveOptionalPivotRelationshipsWithCustomAccessor()
447475
{
448476
Route::get('/', function () {

0 commit comments

Comments
 (0)