1

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')
                            ->get();

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

Ideally, I would like to generate a $request 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 for loop.

1 Answer 1

1

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

<?php
$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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.