I've assigned Laravel Query Builder to a variable. It changes when being used

Viewed 2013

it's a WHY-question, not How-to one:)

I have assigned a Query Bulder to a variable $query:

$query = table::where(['id'=>1, 'this_version'=> 1]);
$versions['slug1'] = $query->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);

outputs array with 2(!) sub-arrays:

Array
(
    [slug1] => Array
        (
            [0] => Array
                (
                    [tourist_id] => 1
                    [tourist_version] => 1
                )

            [1] => Array
                (
                    [tourist_id] => 2
                    [tourist_version] => 1
                )

        )

)

But if I add another line using $query between my $query declaration and it's usage in getting $version[2] array, my $version[2] output is shortened to a 1-dimensional array:

$query = previoustour2_tourist::where(['tour2_id'=>$tour->id, 'this_version'=> 1]);
// Added line:
$versions['slug0'] = $query->select('version_created')->first()->version_created;
//
$versions['slug1'] = $query->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);

outputs (note slug1 now has only 1 nested array):

Array
(
    [slug0] => 2017-08-08 08:25:26
    [slug1] => Array
        (
            [0] => Array
                (
                    [tourist_id] => 1
                    [tourist_version] => 1
                )

        )

)

it seems like the like this line:

$versions['slug0'] = $query->select('version_created')->first()->version_created;

has added "first()" method to the original $query . Am I right and, if yes, why does it happen?

1 Answers
Related