Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add support for getting Model morphed alias #38849

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,17 @@ public static function getMorphedModel($alias)
return static::$morphMap[$alias] ?? null;
}

/**
* Get the alias associated with a given Model class name.
*
* @param string $model
* @return false|int|string
*/
public static function getMorphedAlias($model)
{
return array_search($model, static::$morphMap);
}
Comment on lines +468 to +477
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would do something like this:

Suggested change
/**
* Get the alias associated with a given Model class name.
*
* @param string $model
* @return false|int|string
*/
public static function getMorphedAlias($model)
{
return array_search($model, static::$morphMap);
}
/**
* Get the alias associated with a given Model class name.
*
* @param string|\Illuminate\Database\Eloquent\Model $model
* @return string
*/
public static function getMorphedAlias($model)
{
if (! is_string($model)) {
$model = get_class($model);
}
$morphMap = Relation::morphMap();
if (! empty($morphMap) && in_array($model, $morphMap)) {
return array_search($model, $morphMap, true);
}
return $model;
}


/**
* Handle dynamic method calls to the relationship.
*
Expand Down
10 changes: 10 additions & 0 deletions tests/Database/DatabaseEloquentRelationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,16 @@ public function testSettingMorphMapWithNumericKeys()
Relation::morphMap([], false);
}

public function testGettingAliasFromModelClassName()
{
Relation::morphMap(['user' => 'App\User']);

$this->assertEquals(
'user',
Relation::getMorphedAlias('App\User')
);
}

public function testWithoutRelations()
{
$original = new EloquentNoTouchingModelStub;
Expand Down