MasterSith
MasterSith

Reputation: 173

Custom query for database in Laravel

First of all I'm wondering if this is even possible in Laravel?

I have this code:

$master_array = $_POST['master_search_array'];

$count = count($master_array);
$master_string = '';

for($i=0; $i<$count; $i++) {
    if($master_array[$i] == "Dining"){
        $master_string .= "where('dining', 'dining')";
    }
    if($master_array[$i] == "Party"){
        $master_string .= "where('party','party')";
    }
    ....ETC you get the point
}

$tours = DB::table('tours')->$master_string->get();

return $tours;

So at the end I should get something like this:

$tours = DB::table('tours')->where('dining', 'dining)->where('party','party')->get();

How can I do this in laravel, it gives me an error, no matter if I pass it as $master_string or {{$master_string}}.

Upvotes: 0

Views: 49

Answers (2)

aynber
aynber

Reputation: 23011

Use the ability to add wheres to the query along the way.

DB::table('tour')->where(function($query) use ($master_array)
{
    foreach($master_array as $k => $v) {

        if($v == "Dining"){
            $query->where('dining','dining');
        }
        if($v == "Party"){
            $query->where('party','party');
        }
    }
})
->get();

Upvotes: 0

user1669496
user1669496

Reputation: 33058

There is no need for master string. Just use the query builder how it's meant to be used...

    $master_array = $_POST['master_search_array'];

    $count = count($master_array);
    $query = DB::table('tours');

    for($i=0; $i<$count; $i++) {
        if($master_array[$i] == "Dining"){
            $query->where('dining', 'dining');
        }
        if($master_array[$i] == "Party"){
            $query->where('party', 'party');
        }
    }

    $tours = $query->get();

    return $tours;

Upvotes: 2

Related Questions