Home > Net >  Laravel use string from MySQL as variable
Laravel use string from MySQL as variable

Time:07-27

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

$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

CodePudding user response:

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


Some additional thoughts, you could potentially use regex to capture that the stored data is indeed a variable and only grab the first match.

^\$(?:[a-z]||[A-Z])\S 

You can see an example of this over on 3v4l.org where we remove any potential bad stuff from the data but this is a very blacklisted approach and you should always look to take a whitelisted approach. Just hoping this helps down the line somewhere else.

For some explanation, please checkout regex101 where I added some examples how this could be easily escaped and is no way the ultimate solution.

  • Related