monteecristoo’s blog

https://twitter.com/irakaarozo

jenssegers/laravel-mongodb Basic Usage on cloud9 with php7 ①

updated 2018/1/5

Installation

monteecristoo.hatenablog.com

monteecristoo.hatenablog.com

 

Laravel Configuration

@config\app.php

add the service provider

Jenssegers\Mongodb\MongodbServiceProvider::class,

@config/database.php

'mongodb' => [

            'driver'   => 'mongodb',

            'host'     => env('DB_HOST', 'localhost'),

            'port'     => env(27017),

            'database' => env('DB_DATABASE'),

           //  'username' => env('DB_USERNAME'),

           // 'password' => env('DB_PASSWORD'),

            'options'  => [

                'database' => 'admin' // sets the authentication database required by mongo 3

            ] 

        ],

参考:MongoDB \ Driver \ Exception \ AuthenticationException (11) Authentication failed.

github.com

 

Making Laravel Eloquent Model 

php artisan make:model testMongo

@app\testMongo.php

  namespace App;

  use Illuminate/Database/Eloquent/Model;

  use Moloquent;

 

  class testMongo extends Moloquent

  {

    protected $connection = 'mongodb',  // if use multiple dbs

    protected $collection = 'testMongo'  // define the collection

  }

参考:

github.com

 

Making Laravel Migration file

php artisan make:migration create_testMongo_table

or

php artisan make:model testMongo -m

 

@database/migrations/timestamp_create_testMongo_table.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

 

class CreateTestMongoTable extends Migration

{

  public function up()

  {

    Schema::connection('mongodb')->create('testMongo', function(Blueprint table) {

      $table->increments('id');

      $table->timestamps();

      $table->text('body');

    )};

  }

 

  public function down()

  {

    Schema::connection('mongodb')->drop('testMongo');

  }

}

 * using multiple databases

* DON'T use dropIfExists

参考:

github.com

 

./mongod mongoDBを起動

mongo mongoシェルを起動

env('DB_DATABASE') は c9 なので

mongo shell 上で

> use c9

> db.testMongo.insertOne(

  {

    body: "test mongo operation",

    id: 1

  }

)

参考:

MongoDB CRUD Operations — MongoDB Manual 3.6

 

Laravel tinker で確認

php artisan tinker 

>> $test  = App\testMongo::get()