用laravel dingo/api创建产品api

本文介绍如何使用Laravel Dingo API创建一个简易的产品API,包括创建模型及迁移表、定义RESTful路由及控制器方法。

  沿着上一篇来讲,我们来创建一个简单的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"}]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值