user3707264 user3707264 - 1 year ago 110
PHP Question

Use variables in Eloquent query / Laravel 5.2

In my Laravel 5.2 controller, I'm executing a request with Eloquent ORM :

$products = Product::where('first_condition', 'first_condition_value')
->where('second_condition', 'second_condition_value')

This request works fine and gives me a list of the products that match the two conditions.

Ideally, I would like to generate a
variable and use it in my request:

$request = "where('first_condition', 'first_condition_value')->where('second_condition', 'second_condition_value')"

I didn't manage to make this code run.

To give you more perspective, the request can have multiple conditions from 2 to n so I would like to generate it with a

Answer Source

Wrap your extra conditions in an array and loop them as the following snippet:

$query = Product::where('first_condition', 'first_condition_value');

$conditions = array(
    'second_condition' => 'second_condition_value',
    'third_condition' => 'third_condition_value',

foreach ($conditions as $key => $value) {
    $query->where($key, $value);

$products = $query->get();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download