最後一篇就來點輕鬆的吧??
category 的 routes 就只有簡單的兩個
*api.php
// 顯示所有種類
Route::get('categories', 'CategoriesController@index');
// 顯示該種類所含的所有貼文
Route::get('categories/{id}/posts', 'CategoriesController@categoryPosts');
建立 Controller
$ php artisan make:controller CategoriesController
index method
*CategoriesController.php
public function index()
{
return response(['data' => Category::get()]);
}
categoryPosts method
*CategoriesController.php
public function categoryPosts($id)
{
$category = Category::find($id);
if(!is_null($category)){
return response(['data' => $category->posts]);
}
return respoonse(['message' => 'Category not found!']);
}
完整程式碼:
*CategoriesController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
class CategoriesController extends Controller
{
public function index(){
return response(['data' => Category::get()]);
}
public function categoryPosts($id){
$category = Category::find($id);
if(!is_null($category)){
return response(['data' => $category->posts]);
}
return respoonse(['message' => 'Category not found!']);
}
}
30天的鐵人賽在此告一段落,感謝支持!!