2

What i am doing here might be stupid but i am newbie to laravel, I am applying search filters for database using a query. Query is being built using javascript and being passed to laravel function. E.g.

window.open("/filterResults?types="+types);
//types contains a string like "international#global#europe#  etc

Now in Controller i am getting that string types and exploding it to make a query like this

    $tquery = "Where('type',".$typesArray[0].")";
    for($offset=1; $offset < count($typesArray); $offset++) {
        $tquery .= "->orWhere('type', ".$typesArray[$offset].")";
    }

and executing query like this

$firms = Firm::$tquery->get();

it gives me error

Access to undeclared static property: App\Firm::$tquery

How can i do what i want to.

PS. types are checkboxes some of them can be checked or all.

3 Answers 3

4

It's better to use whereIn() method:

$firms = Firm::whereIn('type', $typesArray)->get();

But if you need to use your way, you can do something like this:

$firm = new App\Firm;

foreach ($typesArray as $type) {
    $firm = $firm->orWhere('type', $type);
}

$firms = $firm->get();
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome whereIn Rocks, :) Thanks Man.
1

Did you consider query builder ?

$firmsQuery = (new Firm)->newQuery();

if($request->has('types')) {
    $typesArray =  $request->input('types');

    foreach ($typesArray as $type) {
        $firmsQuery->where(function($query) use ($type) {
            $query->orWhere('type', $type);
        });
    }

}

$firms = $firmsQuery->get();

4 Comments

Non-static method Illuminate\Database\Eloquent\Model::newQuery() should not be called statically, assuming $this from incompatible context
Whoops! Check updated answer please. There was an unintentional mistake. It should be $firmsQuery = (new Firm)->newQuery();
Thankyou for your attention and time, but now the error is Undefined variable: type
Fixed. It supposed to be $typesArray in foreach. foreach ($typesArray as $type)
0

Actually you are using bad style but you can take a look to DB Raw Expressions

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.