larvel php restful_laravel 实现一个简单的 RESTful API
創建一個 Article 資源
php artisan make:resourceArticle
你可以在 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 functionup()
{
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 App\Models;useIlluminate\Database\Eloquent\Model;class Article extendsModel
{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條數據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',]);
}
}
運行填充器命令進行填充表里的數據就有了
php artisan db:seed --class=ArticlesTableSeeder
如果填充多張表的數據填充編輯:databaes/migrations/seeds/DatabaseSeeder.phppublic functionrun()
{$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 functionindex()
{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"}
總結
以上是生活随笔為你收集整理的larvel php restful_laravel 实现一个简单的 RESTful API的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net程序涉及案例_定制小程序
- 下一篇: linux从新手到高手,1.3 养成良好