大家中秋佳節愉快!
歷經補班以及這週工作的酸甜苦辣,終於能讓自己好好放個假了!
但是該寫的鐵人賽仍要繼續下去,我們將昨天提到的 RESTful API 設計加上之前提到 Model、Controller 的概念綜合起來,做一個簡單的新增、刪除、修改、查詢的範例吧!
php artisan make:model Article -m
/database/migrations
底下會有一個檔案,前綴會是 timestamps 2020_XX_XX_XXXXXX_create_articles_table.php
,在 function up()
內新增以下程式碼Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title',100);
$table->text('body');
$table->timestamps();
});
/App/Models/Article.php
新增以下程式碼protected $fillable = ['title','body'];
php artisan migrate
php artisan make:seeder ArticlesTableSeeder
ArticlesTableSeeder.php
這個檔案會自動被建立在 /database/seeds
內,並新增以下程式碼,建立 30 筆假資料public function run(){
factory(\App\Article::class, 30)->create();
}
DatabaseSeeder.php
檔案,並輸入以下程式碼,往後若新增更多資料表,可透過此程式區塊批次新增假資料public function run(){
$this -> call(ArticlesTableSeeder::class);
}
php artisan make:factory ArticleFactory
/database/factories/ArticleFactory
資料夾內,新增下列程式,定義假資料的格式$factory->define(App\Article::class, function (Faker $faker) {
return [
'title' => $faker->sentence($nbWords = 6, $variableNbWords = true),
'body' => $faker->paragraph
];
});
php artisan db:seed --class=ArticlesTableSeeder
php artisan db:seed
# 執行 migrate 時同步放入假資料
php artisan migrate --seed
php artisan make:resource ArticleResource
/route/api.php
設定 API 的 routing,這是 API 請求時會進行的動作。Route::get('articles', [ArticleController::class, 'index']);
Route::get('articles/{id}', [ArticleController::class, 'show']);
Route::post('articles', [ArticleController::class, 'store']);
Route::put('articles/{id}', [ArticleController::class, 'update']);
Route::delete('articles/{id}', [ArticleController::class, 'destroy']);
app/Http/Controllers/
內php artisan make:controller ArticleController --resource
namespace App\Http\Controllers;
use App\Models\Article;
use App\Http\Controllers\Controller;
use App\Http\Resources\ArticleResource;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
public function index()
{
$article = Article::all();
return ArticleResource::collection($article);
}
public function show($id)
{
$article = Article::find($id);
if ($article){
return $article;
}
return 'Article not found!';
}
public function store(Request $request)
{
$article = new Article;
$article->title = $request ->input('title');
$article->body = $request ->input('body');
$article -> save();
return new ArticleResource($article);
}
public function update(Request $request, $id)
{
$article = Article::find($id);
$article->title = $request -> input('title');
$article->body = $request -> input('body');
$article->save();
return new ArticleResource($article);
}
public function destroy($id)
{
$article = Article::findOrfail($id);
if($article->delete()){
return new ArticleResource($article);
}
return 'Error has occurred while deleting!';
}
}
可以使用 Laravel 啟動伺服器的方法,亦或是透過 nginx 啟動。
php artisan serve
# or
sudo service nginx start