jeudi 8 décembre 2016

Cann't insert data into mongodb in laravel

Let me explain all the step that I followed.

I am using LAMP.

First of all I installed laravel , MongoDB and jenssegers/laravel-mongodb pakage. For this I followed This link.

after that I create database , table and insert data using terminal with all success. cheers

Next step is to integrate mongodb with laravel so I add MongoDB connection detail in app/config/database.php file.

'mongodb' => [
        'driver' => 'mongodb',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', 27017),
        'database' => env('DB_DATABASE', 'usedgoodstore'),
    ],

'default' => env('DB_CONNECTION', 'mongodb'),

upto this point all work fine.

next I create route , view , controller , model file and insert code.

routes/web.php

Route::post('/index', 'UserController@index');

welcome.blade.php

<form action="" method="post">
                <input name="_token" type="hidden" value=""/>
                First name:<br>
                <input type="text" name="firstname">
                <br>
                Last name:<br>
                <input type="text" name="lastname">
                <br><br>
                <input type="submit" value="Submit">
            </form>

UserController.php

<?php
namespace App\Http\Controllers;

use App\Model\User;

use Illuminate\Http\Request;

class UserController  extends Controller{

protected $user;

public  function __construct(User $user){
    $this->user = $user;
}

public function Index(Request $request){

    $data = array('firstname' => $request['firstname'], 'lastname' => $request['lastname']);

    $user = $this->user->PostUser($data);

    return response()->json($user,200);

}


}

User.php (model file)

<?php
namespace App\Model;

use Jenssegers\Mongodb\Eloquent\Model as Moloquent;

use DB; // if I use and not use  this statment and then getting diffrent errors

class User extends Moloquent {

protected $connection = 'mongodb';

protected $collection = 'user';


public function PostUser($data){




        $insertData = DB::collection('user')->insert($data); // I'm getting error on this line.
    if($insertData){
        return true;
    }

}

}

Error I'm getting is :

FatalThrowableError in User.php line 25: Class 'App\Model\DB' not found

If I add use db in User.php (model file) I'm getting below error.

FatalThrowableError in DatabaseManager.php line 317: Call to undefined method Illuminate\Database\MySqlConnection::collection()

Can anyone help me get out of this situation. I am not getting what I miss?

Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire