Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel use string from MySQL as variable

Good night, I have a code that substitutes the data from the request and displays it, like this:

    $client = User::find($data['$id']);
    $execute = 'Send command ';
    $execute .=  $client->id;
    dd($execute);

It return

^ "Send command 1"

Everything is working.
But I want that if I add a variable to the database, for example, like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$client->id

, and call it, then I need the code to process it as a variable, and not as a string, how to do this, thanks)

Example:
(inside the variable $cliend in the database will be the following code:

$client->id

Code:

 $client = DB::table('users')->where('id', $id)->value('id');
    $execute = 'Send command ';
    $execute .=  $client;
    dd($execute);

It is necessary that this variable be executed as a variable. and returned its value not from the database, but as in the first example

>Solution :

Having to store variable names into the database is extremely bad practice although PHP does natively support variables variable.

In your case, I do not see how you could implement this against an object without having to eval some additional code against, assumingly, untrusted user input.

I would first suggest redesigning your database logic to avoid this but if this is necessary or/and your data is controlled then here is a solution:

// Your object you want to access the value of
$client = (object) ['id' => 1];

// Data from your SQL statement that stores that variable name
$databaseValue = '$client->id';

// Eval and store result as variable
eval("\$value = {$databaseValue};");

// Result: Send command 1
echo "Send command {$value}";

See it working over at 3v4l.org

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading