Laravel-mongodb: Is it possible to rename collection?

Created on 12 Nov 2014  路  7Comments  路  Source: jenssegers/laravel-mongodb

I did a quick search on the code and didn't see anything regarding renaming a collection. Is this possible and I'm missing it? Using the below throws an error.

Schema::connection('mongodb')->rename('subjectdocs', 'subjects');
[ErrorException]
Argument 2 passed to Illuminate\Database\Schema\Blueprint::build() must be
an instance of Illuminate\Database\Schema\Grammars\Grammar, null given, cal
led in /vagrant/mysite/vendor/laravel/framework/src/Illuminate/Database/Sc
hema/Builder.php on line 169 and defined

In the meantime, I'm simply running the shell

db.subjectdocs.renameCollection('subjects')

Most helpful comment

I know it looks ugly, but try the following in the meanwhile :)

$db = config('database.connections.mongodb.database');

DB::connection('mongodb')->getMongoClient()->admin->command([
    'renameCollection' => "{$db}.ORIGINAL_NAME",
    'to' => "{$db}.NEW_NAME",
]);

It follows the original PHP spec : http://php.net/manual/en/mongodb.command.php

All 7 comments

You can use :

DB::statement("db.subjectdocs.renameCollection('subjects')");

Thanks.

So i am trying to do the same thing with laravel 5.2 and mongodb and I cannot get the DB::statement("..."); to work properly. Any advice?

php artisan migrate

[SymfonyComponent\Debug\ExceptionFatalThrowableError]
Call to a member function prepare() on null

I know it looks ugly, but try the following in the meanwhile :)

$db = config('database.connections.mongodb.database');

DB::connection('mongodb')->getMongoClient()->admin->command([
    'renameCollection' => "{$db}.ORIGINAL_NAME",
    'to' => "{$db}.NEW_NAME",
]);

It follows the original PHP spec : http://php.net/manual/en/mongodb.command.php

Same, when I try:
Schema::connection('mongodb')->rename('table1', 'table2');
I get this error on type >php artisan migrate:
Type error: Argument 2 passed to Illuminate\Database\Schema\Blueprint::build() must be an instance of Illuminate\Database\Schema\Grammars\Grammar, null given, called in /home /vagrant/code/adinton/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.p hp on line 252

and trying this
DB::statement("db.table1.renameCollection('table2')");
on type >php artisan migrate:
Call to a member function prepare() on null

@peterver your solution works!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kschethan picture kschethan  路  3Comments

tomartailored picture tomartailored  路  3Comments

viacheslavpleshkov picture viacheslavpleshkov  路  3Comments

geofflancaster picture geofflancaster  路  3Comments

Idnan picture Idnan  路  3Comments