Skip to content

Commit 69ebba1

Browse files
author
Admin
committed
fix corner case when a getAttribute is called on an empty Model and the code tried to fetch the relation instead of returning null it threw when returnNullOnInvalidColumnAttributeAccess = false
1 parent 2032ab0 commit 69ebba1

File tree

1 file changed

+25
-20
lines changed

1 file changed

+25
-20
lines changed

src/Models/BaseModel.php

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,23 @@ public function shouldReturnNullOnInvalidColumnAttributeAccess(): bool
333333
return $this->returnNullOnInvalidColumnAttributeAccess;
334334
}
335335

336+
/**
337+
* @inheritdoc
338+
* @throws \Exception
339+
*/
340+
public function getAttribute($key): mixed
341+
{
342+
if ((string)$key === '') {
343+
return null;
344+
}
345+
346+
if (\in_array($key, $this->getColumns(), true)) {
347+
return $this->getAttributeValue($key);
348+
}
349+
350+
return parent::getAttribute($key);
351+
}
352+
336353
/**
337354
* @inheritDoc
338355
* @throws \Exception
@@ -397,29 +414,17 @@ public function attributeOffsetExists(string $offset): bool
397414
*/
398415
public function getRelationValue($key): mixed
399416
{
400-
// If the key already exists in the relationships array, it just means the
401-
// relationship has already been loaded, so we'll just return it out of
402-
// here because there is no need to query within the relations twice.
403-
if ($this->relationLoaded($key)) {
404-
return $this->relations[$key];
405-
}
406-
407-
if (!$this->isRelation($key)) {
408-
if (!$this->returnNullOnInvalidColumnAttributeAccess) {
409-
throw new \Exception('Undefined relation: ' . $key . ' in model: ' . static::class);
410-
}
417+
$value = parent::getRelationValue($key);
411418

412-
return null;
413-
}
414-
415-
if ($this->preventsLazyLoading) {
416-
$this->handleLazyLoadingViolation($key);
419+
if (
420+
$value === null
421+
&& !$this->isRelation($key)
422+
&& !$this->returnNullOnInvalidColumnAttributeAccess
423+
) {
424+
throw new \Exception('Undefined relation: ' . $key . ' in model: ' . static::class);
417425
}
418426

419-
// If the "attribute" exists as a method on the model, we will just assume
420-
// it is a relationship and will load and return results from the query
421-
// and hydrate the relationship's value on the "relationships" array.
422-
return $this->getRelationshipFromMethod($key);
427+
return $value;
423428
}
424429

425430
/**

0 commit comments

Comments
 (0)