iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 25
1
Software Development

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

Day 25 : 貼文 ( Controller : update & destroy )

此兩種方法其實與 user 的部份大致雷同,也是先經過 middleware 檢查後才可執行。

  • update

    • 檢查使用者輸入 ( 同樣並非每一項都是必填 )

      $rules = [
          'title' => 'string|min:2|max:500',
          'content' => 'string|min:2|max:1500'
      ];
      
      $validator = Validator::make($request->all(), $rules);
      if($validator->fails()){
          return response(['message' => $validator->errors()]);
      }
      
    • 確認該使用者存在與否,若存在就做修改貼文的動作

      $post = Post::find($id);
      
      if(!is_null($post)){
          $post->update($request->only(['title', 'content']));
          return response(['data' => $post]);
      }
      
      return response(['message' => 'Post not found!']);
      

    完整程式碼
    *PostsController.php

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;
    use App\Post;
    use App\User;
    
    class PostsController extends Controller
    {
         public function update(Request $request, $id)
        {
            $rules = [
                'title' => 'string|min:2|max:500',
                'content' => 'string|min:2|max:1500'
            ];
    
            $validator = Validator::make($request->all(), $rules);
            if($validator->fails()){
                return response(['message' => $validator->errors()]);
            }
    
            $post = Post::find($id);
    
    
            if(!is_null($post)){
                $post->update($request->only(['title', 'content']));
                return response(['data' => $post]);
            }
    
            return response(['message' => 'Post not found!']);
        }
    }
    
  • destroy
    此處也是檢查該貼文存在與否,存在的話就可刪除

    完整程式碼
    *PostsController.php

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;
    use App\Post;
    use App\User;
    
    class PostsController extends Controller
    {
         public function destroy($id)
        {
            $post = Post::find($id);
            if(!is_null($post)){
                $post->delete();
                return response(['message' => 'Post deleted!!']);
            }
    
            return response(['message' => 'Post not found!']);
        }
    }
    

Postman 測試

為了簡潔重複過的步驟,此處不一一做錯誤的測試

  • update

    image alt

  • delete

    image alt

然而到此為止依舊有些奇怪,詳情請見下一篇。


上一篇
Day 24 : 貼文 ( controller -- userPosts ) [ eloquent relationship method ]
下一篇
Day 26 : Policy authorization
系列文
從零開始的Laravel RESTful api30

尚未有邦友留言

立即登入留言