创建一个 Article 资源
php artisan make:resource Article
你可以在 app/Http/Resources 目录下看到你刚刚生成的 Article 资源
当然我们还需要 Article 的数据库迁移、模型和控制器。我们能用这个命令快速的创建这些。 创建相关的model和contrlloer
php artisan make:model Models/Article -mc
修改迁移文件:跟目录databaes/migrations/2018_11_02_062640_create_articles_table 具体字段类型和索引,请参考https://laravelacademy.org/post/6171.html public function up() { Schema::create('articles'/*表名*/, function (Blueprint $table) { $table->/*字段类型 主键,默认11*/increments('uid')->comment('用户id');//字段和备注 $table->/*字段类型 varchar 30*/string('username','60')->/*唯一索引*/unique()->comment('用户名称'); $table->/*字段类型 varchar 30*/string('email','30')->unique()->comment('用户邮箱'); $table->ipAddress('ipAddress')->comment('ip地址'); $table->timestamps(); }); }
然后我们运行命令创建对应数据表(然后你的数据库中就会生成 migrations//迁移文件表 articles//你创建的表): php artisan migrate //如表结构填错了可执行回滚操作重新创建 php artisan migrate:rollback
回到我们的model层:fillable 里面的字段我们可以进行create和update <?php namespace AppModels; use IlluminateDatabaseEloquentModel; class Article extends Model { protected $fillable = ['username', 'email', 'ipAddress']; }
laravel 自带的有个填充数据的工具为我们添加测试数据: 填充器说明:https://laravelacademy.org/post/9153.html 就会成功一个databaes/migrations/seeds/ArticlesTableSeeder.php文件 php artisan make:seeder ArticlesTableSeeder
然后编辑databaes/migrations/seeds/ArticlesTableSeeder.php文件:填充50条数据 use AppModelsArticle; //修改run方法Article::create里面的字段就是 //protected $fillable = ['username', 'email', 'ipAddress']; public function run() { // Let's truncate our existing records to start from scratch. Article::truncate(); $faker = FakerFactory::create(); // And now, let's create a few articles in our database: for ($i = 0; $i < 50; $i++) { Article::create([ 'username' => $faker->name.str_random(5), 'email' => str_random(10).'@baidu.com', 'ipAddress' => '127.0.0.1', ]); } } 运行填充器命令进行填充表里的数据就有了 php artisan db:seed --class=ArticlesTableSeeder
如果填充多张表的数据填充编辑:databaes/migrations/seeds/DatabaseSeeder.php public function run() { $this->call(ArticlesTableSeeder::class);//填充articles $this->call(InfoTableSeeder::class);//填充info } //然后执行,php artisan db:seed 编辑ArticleController.phpEloquent操作可以参考https://learnku.com/articles/6356/laravel-eloquent-usage: //查询所有 public function index() { return Article::all(); } //根据uid public function show($uid) { //Article::where(['uid'=>$uid])->first(); return Article::where('uid',$uid)->first(); } 添加路由
Route::get('articles/{uid}', 'ArticleController@show');
一个简单接口功能就实现了
http://127.0.0.1:8081/api/articles/1 {"uid":1,"username":"Mr. Jamie Mohruwec7","email":"9gihcYEVzk@baidu.com","ipAddress":"127.0.0.1","created_at":"2018-11-02 07:13:26","updated_at":"2018-11-02 07:13:26"}