流明-mongodb-jenssegers/laravel-mongodb-邮递员 [英] Lumen - mongodb - jenssegers/laravel-mongodb - postman

查看:91
本文介绍了流明-mongodb-jenssegers/laravel-mongodb-邮递员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Wamp上安装了mongodb, C:\ wamp64 \ bin \ mongodb \ mongodb.3.4 \ bin ,我在路径中添加了mongodb,并创建Windows服务以在必要时启动它. 我已经通过composer安装了流明,然后安装了:

i have install mongodb on my wamp, C:\wamp64\bin\mongodb\mongodb.3.4\bin, i have add mongodb in the path, and create windows service to launch it when necessary. I have install lumen through composer, and after that i have install:

  • "laravel/lumen-framework":"5.3.*",
  • "barryvdh/laravel-ide-helper":"v2.2.1",
  • jenssegers/laravel-mongodb:"v3.1.3"
  • "jenssegers/mongodb-session":"v1.1.0"
  • "laravel/lumen-framework": "5.3.*",
  • "barryvdh/laravel-ide-helper": "v2.2.1",
  • jenssegers/laravel-mongodb: "v3.1.3"
  • "jenssegers/mongodb-session": "v1.1.0"

最后,我在wamp php上安装了 mongodb.dll ,并在php.ini中添加了extension = php_mongodb.dll. 现在,mongodb上的扩展名已启用.

Finaly i have install mongodb.dll on my wamp php and add extension=php_mongodb.dll inside the php.ini. And now the extension on mongodb is active.

这是我的User类:

This is my User class:

这是我的迁移

    <?php

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

    class CreateUsersTable extends Migration
    {
        /**
         * The name of the database connection to use.
         *
         * @var string
         */
        protected $connection = 'mongodb';

        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::connection($this->connection)->
            table('Users', function (Blueprint $collection) {
                $collection->index('id');
                $collection->string('name');
                $collection->string('surname');
                $collection->unique('username');
                $collection->string('password',64);
                $collection->timestamps();
            });
        }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::connection($this->connection)
            ->table('Users', function (Blueprint $collection)
            {
                $collection->drop();
            });
    }
}`

这是.env文件

APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=UTC

DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

MONGODB_HOST=localhost
MONGODB_PORT=27017
MONGODB_USERNAME=joy
MONGODB_PASSWORD=mongo@ad@joy
MONGODB_DATABASE=brasserie
MONGODB_AUTHDATABASE=admin

CACHE_DRIVER=file
SESSION_DRIVER=file

我在根应用程序中创建了config目录,并添加了一个database.php配置文件:

i have create config directory in the root app, and i have add a database.php config file:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | PDO Fetch Style
    |--------------------------------------------------------------------------
    |
    | By default, database results will be returned as instances of the PHP
    | stdClass object; however, you may desire to retrieve records in an
    | array format for simplicity. Here you can tweak the fetch style.
    |
    */

    'fetch' => PDO::FETCH_CLASS,

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [



        'mongodb' => array(
            'driver'   => 'mongodb',
            'host'     => env('MONGODB_HOST', '127.0.0.1'),
            'port'     => env('MONGODB_PORT', 27017),
            'username' => env('MONGODB_USERNAME', 'root'),
            'password' => env('MONGODB_PASSWORD', 'testbrasserie'),
            'database' => env('MONGODB_DATABASE', 'synthese'),
           'options' => array(
                'db' => env('MONGODB_AUTHDATABASE', 'admin') //Sets the auth DB
            )//*/
        ),

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer set of commands than a typical key-value systems
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'cluster' => env('REDIS_CLUSTER', false),

        'default' => [
            'host'     => env('REDIS_HOST', '127.0.0.1'),
            'port'     => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DATABASE', 0),
            'password' => env('REDIS_PASSWORD', null),
        ],

    ],//*/

];

我已经启用了雄辩的,facades和jessenger Service提供商.所以这是我的boostrap/app.php:

I have enable eloquent, facades and jessenger Service provider. so this is my boostrap/app.php:

<?php

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

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

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

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

$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::class,
    App\Exceptions\Handler::class
);

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

/*
|--------------------------------------------------------------------------
| 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([
//    App\Http\Middleware\ExampleMiddleware::class
// ]);

// $app->routeMiddleware([
//     'auth' => App\Http\Middleware\Authenticate::class,
// ]);

/*
|--------------------------------------------------------------------------
| 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::class);
// $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);


if ($app->environment() !== 'production') {
    $app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}

//class_alias ('Jenssegers\Mongodb\Eloquent\Model', 'Moloquent');
$app->register('Jenssegers\Mongodb\MongodbServiceProvider');

$app->withEloquent();
/*
|--------------------------------------------------------------------------
| 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.
|
*/



$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../routes/web.php';
});

$app->configure('database');

return $app;

这是我的UsersTableSeeder:

Here is my UsersTableSeeder:

我启动了artisan migration:install,然后启动artisan migration,最后启动了artisan db:seed,这似乎还可以,这是mongo内部的结果:

I have launch the artisan migrate:install then artisan migrate and finally artisan db:seed and it seems to be ok, here is the result inside mongo:

然后我创建了一个UserController

Then i have create a UserController

<?php
/**
 * Created by PhpStorm.
 * User: Joy_Admin
 * Date: 09/12/2016
 * Time: 23:23
 */

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use DB;


class UserController extends Controller
{


    /**
     * Pour recupérer tous les utilsateurs de la BD
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $users = User::all();
        return response()->json($users);
    }

    /**
     * Pour recupérer tous les utilsateurs de la BD
     * @return \Illuminate\Http\JsonResponse
     */
    public function test()
    {

        return response()->json("it's ok");
    }

    /**
     * pour enregistrer un nouvel utilisateur dans la base de données
     * @param Request $request
     */
    public function create(Request $request)
    {

        $user = new User();

       $user->name = $request->input('name');
      $user->surname = $request->input('surname');
       $user->username = $request->input('username');
       $user->password = Hash::make($request->input('password'));
        $user->save();//*/


        DB::collection('Users')->insert([
            'name'     => 'name1',
            'surname' => 'surname1',
            'username'    => 'username1',
            'password' => Hash::make('password1')
        ]);
        return response()->json($user);

    }


    /**
     * On renvoit l'individu dans la BD
     * correspondant à l'id spécifié
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function get($id)
    {
        $user = User::find($id);

        return response()->json($user);
    }

    /**
     * Mettre à jour les informations sur un utilisateur de la BD
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request,$id)
    {
        $user = User::find($id);

        $user->name = $request->input('name');
        $user->surname = $request->input('surname');
        $user->username = $request->input('username');
        $user->password = Hash::make($request->input('password'));

        $user->save();

        return response()->json($user);
    }

    public function delete($id)
    {
        $user = User::find($id);

        $user->delete();

        return response()->json('Success');

    }
}

最后更新我的路线/web.php

And finally update my routes/web.php

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

use App\Http\Controllers\UserController;



$app->get('/', function () use ($app) {
    return $app->version();
});

$app->get('/api/users','UserController@index');
$app->get('/api/users/{id}','UserController@get');
$app->post('/api/users','UserController@create');
$app->put('/api/users/{id}','UserController@update');
$app->delete('/api/users/{id}','UserController@delete');
$app->get('/api','UserController@test');

我已经启动了邮递员,以便可以测试我的应用, 只有/api 起作用,所有其他路由都给我同样的错误

I have launch postman, so that i could test my app, only /api work, all the other route give me the same error

有人可以帮我解决问题吗?

Could somebody help me fix the problem?

Openssl和curl在我的wamp php中处于活动状态.

Openssl and curl are active in my wamp php.

推荐答案

我已经解决了这个问题, 在我的.env中,我有:

I have solve the problem, in my .env i was having:

CACHE_DRIVER=file
SESSION_DRIVER=file

但是在我的项目中没有为它们配置,所以当我将其更改为

but in my project no configuration for them, so when i have change it into

CACHE_DRIVER=
SESSION_DRIVER=

现在一切正常.

这篇关于流明-mongodb-jenssegers/laravel-mongodb-邮递员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆