Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dkBITS's avatar
Level 13

PHP Snippet Rule from database field

Hi,

Any best practice tip here how to save rules as php code in database field and run this rules later in my Laravel code?

Like: amount>10;$discount=10;$discount=0;

So if amount is bigger the 10 give 10% on this otherwise 0. Eval() is not what i expected, doesn‘t it?

Or any rule definition package is well known?

Thx

0 likes
1 reply
LaryAI's avatar
Level 58

One solution could be to use a PHP parser library like PHP-Parser to parse the PHP code stored in the database field and execute it. However, this approach can be risky as it can execute arbitrary code and potentially harm the system. A safer approach would be to define a custom syntax for the rules and write a parser for it. For example, the rule could be defined as a JSON object with a specific structure, and the parser would validate and execute it. Here's an example implementation:

// Rule stored in database field
$rule = '{"condition": "amount > 10", "true": {"discount": 10}, "false": {"discount": 0}}';

// Parse the rule
$ruleData = json_decode($rule, true);

// Validate the rule structure
if (!isset($ruleData['condition'], $ruleData['true'], $ruleData['false'])) {
    throw new Exception('Invalid rule structure');
}

// Evaluate the condition
$amount = 15; // Example value
$condition = $ruleData['condition'];
if (!eval("return $condition;")) {
    throw new Exception('Condition evaluation failed');
}

// Execute the true or false branch
$discount = $ruleData[$condition ? 'true' : 'false']['discount'];
echo "Discount: $discount"; // Output: Discount: 10

In this example, the rule is defined as a JSON object with three keys: condition, true, and false. The condition key contains a PHP expression that evaluates to a boolean value. The true and false keys contain objects with the variables and values to set if the condition is true or false, respectively. The parser validates the rule structure and evaluates the condition using eval(). Finally, it executes the true or false branch and sets the variables accordingly.

Please or to participate in this conversation.