Matthew
Matthew

Reputation: 1655

Eloquent variable query issue in Laravel

I have a relatively simple variable set that seems to work out fine, but I believe it is how I am outputting it that creates an issue.

At the moment I use the following in my controller:

    if(empty($_GET['direction'])){
        $direction = "'LIKE', '%'";
        } else if ($_GET['direction'] === 'Inbound') {
        $direction = "'>', 1";
        } else if ($_GET['direction'] === 'Outbound'){
        $direction = "'=', 1";
    }

Now, I have dd'd the $direction after the fact and every test shows that it accurately chose the correct variable option given the value of $_GET['direction'].

My problem lies with how I am either outputting it there or inputting the results in the below section:

$manifests = DB::table('carrier_manifests')
        ->join('customers', 'carrier_manifests.carrierOrigin', '=', 'customers.id')
        ->select('carrier_manifests.*', 'customers.customer_name')  

        ->where([
                    ['manifestNumber', 'LIKE', '%' . $manifest . '%'],
                    ['originTerminal','LIKE','%' . $terminal . '%'],
                    ['carrierOrigin', $direction],
                ])
        ->orderBy('dateUnloaded', 'DESC')
        ->whereBetween('dateUnloaded', [$startDate, $endDate])
        ->limit(100)
        ->get();

Now, before I go on, I will say that everything works correctly here and has for some time, it's when the carrierOrigin and $direction are added that there is an issue.

For example if I leave the direction field empty on the page, it will set the $direction variable as equal to "'LIKE', '%'".

Unfortunately, in the where clause, this isn't sent well or something, as it returns no results, but as a test if I change the this line:

['carrierOrigin', $direction],

to

['carrierOrigin','LIKE','%'],

it returns all of the results successfully. So is there a different way I should format the output or send the output?

Upvotes: 0

Views: 56

Answers (1)

train_fox
train_fox

Reputation: 1537

You are passing string as second and third where arguments. Use this in controller:

if(empty($_GET['direction'])){
    $direction = ['LIKE', '%'];
    } else if ($_GET['direction'] === 'Inbound') {
    $direction = ['>', 1];
    } else if ($_GET['direction'] === 'Outbound'){
    $direction = ['=', 1];
}

Then on query:

$manifests = DB::table('carrier_manifests')
    ->join('customers', 'carrier_manifests.carrierOrigin', '=', 'customers.id')
    ->select('carrier_manifests.*', 'customers.customer_name')  

    ->where([
                ['manifestNumber', 'LIKE', '%' . $manifest . '%'],
                ['originTerminal','LIKE','%' . $terminal . '%'],
                ['carrierOrigin', $direction[0], $direction[1],
            ])
    ->orderBy('dateUnloaded', 'DESC')
    ->whereBetween('dateUnloaded', [$startDate, $endDate])
    ->limit(100)
    ->get();

Upvotes: 1

Related Questions