iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 30
1
Software Development

從零開始的Laravel RESTful api系列 第 30

Day 30 : category ( api routes & controller -- index & categoryPosts )

最後一篇就來點輕鬆的吧??

api routes

category 的 routes 就只有簡單的兩個

*api.php

// 顯示所有種類
Route::get('categories', 'CategoriesController@index');

// 顯示該種類所含的所有貼文
Route::get('categories/{id}/posts', 'CategoriesController@categoryPosts');

Controller

  • 建立 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!']);
    }
}

Postman 實測

  • index

image alt

  • categoryPosts

image alt

30天的鐵人賽在此告一段落,感謝支持!!


上一篇
Day 29 : category ( modify PostsController )
系列文
從零開始的Laravel RESTful api30

1 則留言

0
Howard
iT邦新手 5 級 ‧ 2019-10-16 22:06:03

賀完賽/images/emoticon/emoticon64.gif

我要留言

立即登入留言