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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With