用laravel dingo/api创建产品api

  沿着上一篇来讲,我们来创建一个简单的item产品api,也是用到laravel dingo/api来实现,对dingo/api不熟的朋友可以翻看前面的文章。好,我们随着ytkah一起来创建产品api

  1,创建model并生成迁移表(-m表示)

php artisan make:model Item -m

  生成了一个model(/app/Item.php)和迁移表

  迁移表在/database/migrations/**_create_items_table.php,添加相应的字段name,price,img,description(id和timestamps一般都会有的字段)

public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->double('price');
            $table->string('img');
            $table->text('description');
            $table->timestamps();
        });
    }

  保存文件

  在命令行中输入

php artisan migrate

  这个指令是将上面做好的迁移表插入到数据库中,打开数据库,看看是不是多了一个items的表,里面带有相应的字段

migrate迁移表

  

  2,创建routes

  打开/routes/api.php,添加一个test路由

$api->get('test', 'App\Api\Controllers\HelloController@test'); 

  3,添加controller

  打开/app/Api/Controllers/HelloController.php,添加

use App\Item;

  还有调用item的方法

public function test()
    {
        $items = Item::all();
        return $items;
    }

  测试一下是不是有问题http://www.z5w.net/api/test,看看是不是显示成功

[{"id":1,"name":"ipod","price":367.87,"img":"empty","descriptionx":"nice misic player","created_at":"2018-07-09 00:00:00","updated_at":"2018-07-09 10:12:15"}]

猜你喜欢

转载自www.cnblogs.com/ytkah/p/9284421.html