Home > Enterprise >  Laravel Mutator Database Value with Variable variables
Laravel Mutator Database Value with Variable variables

Time:12-03

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.

CodePudding user response:

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;
  • Related