使用Laravel框架创建MongoDB的API
我将使用Laravel创建一个读取MongoDB集合数据的API。
MongoDB的数据与下列内容相同。
使用Laravel以表格形式显示MongoDB的数据。
使用以下库:
jenssegers/laravel-mongodb
1)创建项目
laravel new api02
cd api02
composer require jenssegers/mongodb
2) 编辑config/app.php
'providers' => [
// 略
Jenssegers\Mongodb\MongodbServiceProvider::class,
],
'aliases' => [
// 略
'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
],
3) 编辑 .env
#DB_CONNECTION=mysql
#DB_HOST=127.0.0.1
#DB_PORT=3306
#DB_DATABASE=homestead
#DB_USERNAME=homestead
#DB_PASSWORD=secret
DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=city_db
4) 编辑 config/database.php
'default' => env('DB_CONNECTION', 'mongodb'),
// 略
'connections' => [
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
],
5) 清除缓存
php artisan cache:clear
6) 创建模型
mkdir app/Models
php artisan make:model Models/City
7) 模型的编辑
<?php
namespace App\Models;
class City extends \Moloquent
{
protected $collection = 'saitama';
}
8) 编辑 routes/api.php
// 略
Route::group(['middleware' => ['api']], function(){
Route::resource('city', 'Api\CityController');
Route::get('all', 'Api\CityController@all');
Route::get('find/{id}', 'Api\CityController@find');
Route::get('where/{name}', 'Api\CityController@where');
Route::get('between/{min}/{max}', 'Api\CityController@between');
});
9) 创建控制器
php artisan make:controller Api/CityController
10)编辑控制器
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\City;
class CityController extends Controller
{
public function index()
{
$cities = City::orderBy('_id', 'desc')->get();
return $cities;
}
public function all()
{
$cities = City::all();
return $cities;
}
public function find($id)
{
$cities = City::find($id);
return $cities;
}
public function where($name)
{
$cities = City::where('name','=',$name)->get();
return $cities;
}
public function between($min,$max)
{
$cities = City::whereBetween('population',[(int)$min,(int)$max])->get();
return $cities;
}
}
11) 服务器启动
php artisan serve --host 0.0.0.0
12) 使用客户端进行访问
curl http://localhost:8000/api/city
curl http://localhost:8000/api/all
curl http://localhost:8000/api/find/5b2c483e6fc1214d33e6151c
curl http://localhost:8000/api/where/久喜
curl http://localhost:8000/api/between/30000/50000