larvel php restful_laravel 实现一个简单的 RESTful API
創(chuàng)建一個 Article 資源
php artisan make:resourceArticle
你可以在 app/Http/Resources 目錄下看到你剛剛生成的 Article 資源
當(dāng)然我們還需要 Article 的數(shù)據(jù)庫遷移、模型和控制器。我們能用這個命令快速的創(chuàng)建這些。
創(chuàng)建相關(guān)的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 functionup()
{
Schema::create('articles'/*表名*/, function (Blueprint $table) {$table->/*字段類型 主鍵,默認(rèn)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();
});
}
然后我們運(yùn)行命令創(chuàng)建對應(yīng)數(shù)據(jù)表(然后你的數(shù)據(jù)庫中就會生成 migrations//遷移文件表 articles//你創(chuàng)建的表):
php artisan migrate//如表結(jié)構(gòu)填錯了可執(zhí)行回滾操作重新創(chuàng)建
php artisan migrate:rollback
回到我們的model層:fillable 里面的字段我們可以進(jìn)行create和update<?php
namespace App\Models;useIlluminate\Database\Eloquent\Model;class Article extendsModel
{protected $fillable = ['username', 'email', 'ipAddress'];
}
laravel 自帶的有個填充數(shù)據(jù)的工具為我們添加測試數(shù)據(jù):
填充器說明:https://laravelacademy.org/post/9153.html
就會成功一個databaes/migrations/seeds/ArticlesTableSeeder.php文件
php artisan make:seeder ArticlesTableSeeder
然后編輯databaes/migrations/seeds/ArticlesTableSeeder.php文件:填充50條數(shù)據(jù)useApp\Models\Article;//修改run方法Article::create里面的字段就是
//protected $fillable = ['username', 'email', 'ipAddress'];
public functionrun()
{//Let's truncate our existing records to start from scratch.
Article::truncate();$faker = \Faker\Factory::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',]);
}
}
運(yùn)行填充器命令進(jìn)行填充表里的數(shù)據(jù)就有了
php artisan db:seed --class=ArticlesTableSeeder
如果填充多張表的數(shù)據(jù)填充編輯:databaes/migrations/seeds/DatabaseSeeder.phppublic functionrun()
{$this->call(ArticlesTableSeeder::class);//填充articles
$this->call(InfoTableSeeder::class);//填充info
}//然后執(zhí)行,php artisan db:seed
編輯ArticleController.phpEloquent操作可以參考https://learnku.com/articles/6356/laravel-eloquent-usage:
//查詢所有
public functionindex()
{return Article::all();
}//根據(jù)uid
public function show($uid)
{//Article::where(['uid'=>$uid])->first();
return Article::where('uid',$uid)->first();
}
添加路由
Route::get('articles/{uid}', 'ArticleController@show');
一個簡單接口功能就實(shí)現(xiàn)了
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"}
總結(jié)
以上是生活随笔為你收集整理的larvel php restful_laravel 实现一个简单的 RESTful API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net程序涉及案例_定制小程序
- 下一篇: php 什么时候传引用,什么时候在PHP