monteecristoo’s blog

jenssegers/laravel-mongodb Basic Usage on cloud9 with php7⑦ convert mongoDB to Mysql

  1. setting up Mysql Relationships
  2. create the route and controller 
  3. fetch the data from mongoDB
  4. extract the value from the response(3)
  5. fetch the data from Mysql using the value(4)
  6. return the response



    use Jenssegers\Mongodb\Eloquent\HybridRelations;

    use App\MongoMessage;

    class User extends Authenticatable
      use HybridRelations;

      public function mongoMessages()
        return $this->hasMany(MongoMessage::class);


    use Moloquent;

    use App\User;

    class MongoMessage extends Moloquent
protected $connection = 'mongodb';
protected $collection = 'mongo_messages';

protected $fillable = ['user_id', 'group', 'body', 'receiver'];

public function user()
return $this->belongsTo(User::class);




    Route::get('getMongoMessages', 'mongoController@getMongoMessages');


    public function getMongoMessages{ }




public function mongoMessages()
$mongoMessages = MongoMessage::get(); ③
$mMessages = array();
foreach($mongoMessages as $mongoMessage)
$user_id = $mongoMessage->user_id; ④
$user = User::where('id', $user_id)->first(); ⑤

$addData["name"] = $user->name;
$addData["avatar"] = $user->avatar;
$mongoArray = $mongoMessage->toArray();
$mongoArray += $addData;

array_push($mMessages, $mongoArray);
return $mMessages; ⑥


$mongoMessage->user_id は Mysql Relationships によって mongoMessage が作成された時点で自動的に付与される。

$mMessages は元々の mongoDB から返された値の user_id を使って Mysql base DB の User から name と avatar を取得してそれらが追加された値になる。