Skip to content
Advertisement

Laravel Mutator Database Value with Variable variables

I have the following Laravel Eloquent Mutator

public function getUsedWorkingTimeAttribute($db = null)
{
   return is_null($db) ? $this->getUsedDaysOfKind('working time', true, 120) : $db;
}

When calling $object->used_working_time i get the value stored in the database as expected.

When using Variable variables $object->{'used_'.$name} with $name = 'working_time' the $db value is null.

Is there a way to get the database attribute with the second way. I am using Laravel 8.74 and PHP 8.0.

Advertisement

Answer

Try to create a variable first and then use it with object as bellow: and make sure there is no space in string else replace it with underscore

$variable = 'used_' . $name;
$object->$variable;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement