Tag Archives: Laravel

Laravel, laravel-mongodb, Laravel Forge, and PHP 7

Oookay, so for some reason the mix from the title was a big deal. When you try to install laravel-mongodb package on servers created by Laravel Homestead or Forge – it’s going to fail. To be specific, when you try to run:

composer require jenssegers/mongodb

composer is going to start bitching about missing mongodb php extension. And you can’t install it until you run:

sudo apt-get install libcurl4-openssl-dev

Then you’ll be good to go. Install the new mongodb extension by running:

sudo pecl install mongodb

and then add the following line to your php.ini file (probably /etc/php/7.0/cli/php.ini & /etc/php/7.0/fpm/php.ini):

extension=mongodb.so

That should be it. Don’t forget to restart nginx.

laravel-mongodb – complex query example

Complex queries can be pretty hard to translate. I tried to convert a PostgreSQL query for grouping by a boolean and a date at the same time. Here is my original Eloquent query:

ModelName::selectRaw('COUNT(*) AS "count", boolean_one, date_trunc(\'day\', created_at) as date')
    ->where('created_at', '>=', Carbon::now()->subMonth())
    ->where('boolean_two', '=', $booleanTwo)
    ->where('string_value', 'LIKE', $searchForString . '%')
    ->groupBy('boolean_one')->groupBy('date')
    ->orderBy('date')->get();

And here’s the same query translated, using Moloquent:

ModelName::raw(function ($collection) {
    return $collection->aggregate([
        [
            '$match' => [
                'created_at'   => ['$gt' => new MongoDate(Carbon::now()->subMonths(1)->timestamp)],
                'boolean_two'  => $booleanTwo,
                'string_value' => ['$regex' => new MongoRegex('/.*' . $searchForString . '.*/')]
            ],
        ],
        [

            '$group' => [
                '_id'   => [
                    'month'       => ['$month' => '$created_at'],
                    'day'         => ['$dayOfMonth' => '$created_at'],
                    'year'        => ['$year' => '$created_at'],
                    'boolean_one' => '$boolean_one'
                ],
                'count' => [
                    '$sum' => 1
                ]
            ]
        ]
    ]);
});;