建立一個 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 App\Models;
use Illuminate\Database\Eloquent\Model;
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 App\Models\Article;
//修改run方法Article::create裡面的欄位就是
//protected $fillable = ['username', 'email', 'ipAddress'];
public function run()
{
// 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.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"}