New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lumen support? #470

Closed
lasselehtinen opened this Issue Apr 16, 2015 · 21 comments

Comments

Projects
None yet
@lasselehtinen

lasselehtinen commented Apr 16, 2015

Hi,

I loved using this with Laravel and would like to continue using this on Lumen. I tried the following:

  1. Registered the service provider on bookstrap/app.php with $app->register('Jenssegers\Mongodb\MongodbServiceProvider');
  2. Since Lumen does not have config/database, I had to edit vendor\laravel\lumen-framework\config\database.php to add MongoDB configuration.

But when I actually try to do something, I get:

InvalidArgumentException: Unsupported driver [mongodb]

So I guess even though I register the service provider, it does not create the necessary database connector for MongoDB? I know this Lumen is not officially supported, but is there any chance to get this working?

@84564221

This comment has been minimized.

84564221 commented Apr 16, 2015

Did you uncommented the $app->withEloquent() call in your bootstrap/app.php file?

@lasselehtinen

This comment has been minimized.

lasselehtinen commented Apr 17, 2015

Sorry I forgot to mention that. But yes I did. I just tried migrations and seeding first.

@kieranajp

This comment has been minimized.

Contributor

kieranajp commented Apr 17, 2015

Having the same issue here, albeit I'm not trying migrations & seeding, just attempting to pull from an existing MongoDb database.

As Lumen is just using the Illuminate\Database component I'm sure it's going to be fairly simple to get this all hooked up, but it's Friday afternoon and I'm having too much trouble concentrating to figure it out at the moment :)

@yohang88

This comment has been minimized.

yohang88 commented Apr 19, 2015

I created simple config/database.php to override vendor/laravel/lumen/config/database.php.

<?php

return [

    'default' => 'mongodb',

    'connections' => [

        'mongodb' => array(
            'driver'   => 'mongodb',
            'host'     => 'localhost',
            'port'     => 27017,
            'username' => '',
            'password' => '',
            'database' => 'test_db'
        ),

    ],

    'migrations' => 'migrations',
];

It's works.

@alex-LE

This comment has been minimized.

alex-LE commented Apr 19, 2015

@yohang88 did you make any other changes than adding the service provider to the boostrap/app.php?
I've also created the config file and i get the same "Unsupported driver" error.
How does your model look like?

@bryceadams

This comment has been minimized.

bryceadams commented Apr 20, 2015

Also having trouble with this, same error

@yohang88

This comment has been minimized.

yohang88 commented Apr 20, 2015

@alex-LE
This is my bootstrap/app.php

<?php

require_once __DIR__.'/../vendor/autoload.php';

// Dotenv::load(__DIR__.'/../');

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that servers as the central piece of the framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application;

// $app->withFacades();

// $app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    'Illuminate\Contracts\Debug\ExceptionHandler',
    'App\Exceptions\Handler'
);

$app->singleton(
    'Illuminate\Contracts\Console\Kernel',
    'App\Console\Kernel'
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

// $app->middleware([
//     // 'Illuminate\Cookie\Middleware\EncryptCookies',
//     // 'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
//     // 'Illuminate\Session\Middleware\StartSession',
//     // 'Illuminate\View\Middleware\ShareErrorsFromSession',
//     // 'Laravel\Lumen\Http\Middleware\VerifyCsrfToken',
// ]);

// $app->routeMiddleware([

// ]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register('App\Providers\AppServiceProvider');
$app->register('Jenssegers\Mongodb\MongodbServiceProvider');

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

require __DIR__.'/../app/Http/routes.php';

return $app;

Maybe the tricky setting is $app->withEloquent(); . I'm uncommented that line, and get Unsuporrted Driver also.

This is my Model file User.php

<?php namespace App;

use Jenssegers\Mongodb\Model as Eloquent;

class User extends Eloquent {

    protected $collection = 'users';

}

This is my routes.php for test purpose:


$app->get('/', function() use ($app) {

    $users = App\User::all()->toJson();

    echo $users;

});

Response:

[{"_id":"5533b08eb8b200865f64f21f","nama":"Yoga Hanggara"},{"_id":"5533b0c9b8b200865f64f220","nama":"Handoko"}]
@alex-LE

This comment has been minimized.

alex-LE commented Apr 20, 2015

@yohang88 thanks!
I've disabled $app->withEloquent(); and now it works.
It might be a problem as i'm unable to use Eloquent now, but in my case i don't need it.

@andreipop2005

This comment has been minimized.

andreipop2005 commented Apr 24, 2015

Disabling $app->withEloquent() works, but I consider this a workaround.

@krisanalfa

This comment has been minimized.

krisanalfa commented Apr 27, 2015

Just realized that registering Jenssegers\Mongodb\MongodbServiceProvider after make db via App::withEloquent() will throw Unsupported driver [mongodb].

// bootstrap/app.php

// $app->withFacades();

$app->withEloquent();

$app->register('Jenssegers\Mongodb\MongodbServiceProvider');

But if you register before withEloquent() line, it will be OK.

// bootstrap/app.php

// $app->withFacades();

$app->register('Jenssegers\Mongodb\MongodbServiceProvider');

$app->withEloquent();
@kh411d

This comment has been minimized.

kh411d commented Apr 28, 2015

You may want to use The Capsule Manager and then creating your own mongodb config at project root
https://github.com/illuminate/database/blob/master/README.md
It's more portable I think.

Take advantage by using the middleware to configure mongodb:

<?php 
            namespace App\Http\Middleware;
            use Closure;
            use Illuminate\Database\Capsule\Manager as Capsule;
            use Illuminate\Events\Dispatcher;
            use Illuminate\Container\Container;

            class ExampleMiddleware {

                public function handle($request, Closure $next)
                {
                    $capsule = new Capsule;

                    //Configure config file config/defaultmongodb.php
                    \App::configure('defaultmongodb');
                    $capsule->addConnection(config('defaultmongodb'));

                    // Set the event dispatcher used by Eloquent models... (optional)
                    $capsule->setEventDispatcher(new Dispatcher(new Container));

                    // Make this Capsule instance available globally via static methods... (optional)
                    $capsule->setAsGlobal();

                    // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
                    $capsule->bootEloquent();


                    $capsule->getDatabaseManager()->extend('mongodb', function($config){
                        return new \Jenssegers\Mongodb\Connection($config);
                    });

                    return $next($request);
                }
            }

If you want to make it globally, you need to add it on the bootstrap file bootstrap/app.php

$app->middleware([
    'App\Http\Middleware\ExampleMiddleware',
 ]);
@guns28

This comment has been minimized.

guns28 commented Apr 29, 2015

thx :) @krisanalfa

@krisanalfa

This comment has been minimized.

krisanalfa commented Apr 29, 2015

@askmatey Keep rock, bro!

@guns28 Anytime 😄

@hieuvan

This comment has been minimized.

hieuvan commented Jun 19, 2015

Thank you so much @krisanalfa

@jenssegers

This comment has been minimized.

Owner

jenssegers commented Jun 21, 2015

Could someone add this as a PR to the documentation?

@zahiruldu

This comment has been minimized.

zahiruldu commented May 8, 2016

When I try to install the package it show the following errprs.

Problem 1
- jenssegers/mongodb v3.0.0 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1, 1.0.2].
- jenssegers/mongodb v3.0.1 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1, 1.0.2].
- jenssegers/mongodb v3.0.2 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1, 1.0.2].
- mongodb/mongodb 1.0.2 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.0.1 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.0.0 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system.
- Installation request for jenssegers/mongodb ^3.0 -> satisfiable by jenssegers/mongodb[v3.0.0, v3.0.1, v3.0.2].

@krisanalfa

This comment has been minimized.

krisanalfa commented May 8, 2016

@zahiruldu You have to install PHP MongoDB first. You can do it via PECL installation.

pecl install mongodb
@thxv3n0lvl

This comment has been minimized.

thxv3n0lvl commented Jun 9, 2016

I'm using Laravel Framework version 5.2.35 and the code is kind of different.
Can't use $app->withEloquent() this doesn't exist on laravel's Illuminate

Any update for this version?

<?php

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);


/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);
@kieranajp

This comment has been minimized.

Contributor

kieranajp commented Jun 9, 2016

Looks like you're using Laravel full, this issue is about Lumen. The instructions for the full framework should still work on 5.2.35.

@rafaelcpalmeida

This comment has been minimized.

rafaelcpalmeida commented Feb 20, 2017

@yohang88 solution is working.

My config/database.php looks like:

<?php
    return [
        'default' => 'mongodb',
        'connections' => [
            'mongodb' => [
                'driver'   => 'mongodb',
                'host'     => env('DB_HOST', 'localhost'),
                'port'     => env('DB_PORT', 27017),
                'database' => env('DB_DATABASE'),
                'username' => env('DB_USERNAME'),
                'password' => env('DB_PASSWORD'),
                'options'  => [
                    'database' => 'admin' // sets the authentication database required by mongo 3
                ]
            ],
        ],
        'migrations' => 'migrations',
    ];
@farzan-ghalami

This comment has been minimized.

farzan-ghalami commented May 22, 2018

hi guys
(my english is so bad and excuse me for this format)
after a lot of search into the net,finally figure out how to use 2 different databases (Mongodb and mysql) in LUMEN.

  1. create config directory in root and create new php file into config directory, named database.php (this is so important that name of php file must to be database.php )
    here is my database config file:
    `<?php
    return [
    'default' => 'mongodb',
    'connections' => [

     'mongodb' => [
         'driver' => 'mongodb',
         'host' => 'localhost',
         'port' => 27017 ,
         'database' => 'appstore',
         'username' => 'farzan',
         'password' => '1234admin',
         'options' => [
             'database' => 'admin' // sets the authentication database required by mongo 3
         ]
     ],
    
     'mysql' => [
         'driver' => 'mysql',
         'host' => 'localhost',
         'database' => 'lumen',
         'username' => 'root',
         'password' => null ,
         'charset'   => 'utf8',
         'collation' => 'utf8_unicode_ci',
     ],
    

    ]
    ];

as you see, my default db is mongodb, but you can switch between databases easily when you create a Model class. for example if you want to work with mysql db you have to write:
protected $connection = 'mysql';
this line of code change the default db in database.php
here is my model class
`<?php
namespace App\models;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
protected $connection = 'mysql';
protected $fillable = [
'name', 'model' , 'created_at' , 'updated_at',
];
}and my controller class <?php

namespace App\Http\Controllers;

use App\models\Car;

class CarController extends Controller
{
public function showCars()
{

   $cars = Car::all();
    return response()->json($cars);
}

public function showCar($id)
{
    $cars = Car::find($id);
    return response()->json($cars);
}

}`

enjoy it:))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment