Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Laravel eloquent attribute by string

I am storing some strings in my database, and I want to be able to get model attributes using them.

Basically, I can call a users booking like this

$user->bookings->date

in my controller and it works, and i'm storing a string in my database like this

'user->bookings->date'

How can I use this string from the database to get the attribute? I'm hoping to be able to do something like

$user = User::findOrFail(1);
$string = 'user->bookings->date'; //This is fetched from the db normally
$booking_date = ${$string}; //Instead of writing $user->bookings->date

Is this possible?

like image 371
S_R Avatar asked Sep 17 '25 01:09

S_R


1 Answers

I've found a solution that involves chaining object access from a static string:

$user = User::findOrFail(1);

$string = "user->bookings->date";
$params = explode("->", $string);

$var = null;
foreach($params AS $param){
    if($var){
        $var = $var->{$param};
    } else {
        $var = ${$param};
    }
}

dd($var);

On the first iteration of $params, set $var to the value of ${$param} ($user). Then, on the next iterations, set $var to the value of $var->{$param} ($user->bookings, $user->bookings->date). Then, finally, echo out (or dd()) the value of $var. In my test, this results in

"2019-06-18 12:06:00"

So while it requires a bit of additional logic, it is possible to set object access from a database string.

like image 86
Tim Lewis Avatar answered Sep 18 '25 16:09

Tim Lewis