Skip to content

Commit

Permalink
[9.x] Fix whenPivotLoaded(As) api resource methods when using Eloqu…
Browse files Browse the repository at this point in the history
…ent strict mode (#44792)

* Add failing test

* Use isset method

* Fix linting
  • Loading branch information
gdebrauwer authored Oct 31, 2022
1 parent 05f7a7c commit 4f7ee1d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ protected function whenPivotLoadedAs($accessor, $table, $value, $default = null)
}

return $this->when(
$this->resource->$accessor &&
isset($this->resource->$accessor) &&
($this->resource->$accessor instanceof $table ||
$this->resource->$accessor->getTable() === $table),
...[$value, $default]
Expand Down
28 changes: 28 additions & 0 deletions tests/Integration/Http/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Tests\Integration\Http;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Http\Exceptions\PostTooLargeException;
use Illuminate\Http\Request;
Expand Down Expand Up @@ -443,6 +444,33 @@ public function testResourcesMayHaveOptionalPivotRelationships()
]);
}

public function testResourceDoesNotThrowErrorWhenUsingEloquentStrictModeAndCheckingOptionalPivotRelationship()
{
Model::shouldBeStrict(true);

Route::get('/', function () {
$post = new Post(['id' => 5]);
(function () {
$this->exists = true;
$this->wasRecentlyCreated = false;
})->bindTo($post)();

return new PostResourceWithOptionalPivotRelationship($post);
});

$response = $this->withoutExceptionHandling()->get(
'/', ['Accept' => 'application/json']
);

$response->assertStatus(200);

$response->assertExactJson([
'data' => [
'id' => 5,
],
]);
}

public function testResourcesMayHaveOptionalPivotRelationshipsWithCustomAccessor()
{
Route::get('/', function () {
Expand Down

0 comments on commit 4f7ee1d

Please sign in to comment.