首页 > 解决方案 > API 验证 laravel 5.7

问题描述

我需要用 laravel 5.7 制作一个 api,这个 api 本身不是问题。

例如,我需要对当前模型和嵌套关系对象进行严格验证以进行保存。

想象一个带有关系评论的模型帖子。我已将我的数据存储在数据库中:



    [
      {id: 1, user_id: 1, title: 'my title post', comments: [{id: 5, comment: 'my comment for post id 1'}]},
      {id: 2, user_id: 1, title: 'my second title post', comments: [{id: 15, comment: 'my comment for post id 2'}]},
      {id: 8, user_id: 2, title: 'my third title post', comments: [{id: 25, comment: 'my comment for post id 8'}]}
    ]

我登录 api 的 user_id 是1 如果我尝试发送POST http更新帖子和评论,我如何验证登录的用户api是每个对象的所有者?帖子示例:

发布以更新。



    [
      {id: 1, user_id: 1, title: 'my title post modified', comments: [{id: 5, comment: 'my comment for post id 1'}]},
      {id: 1, user_id: 1, title: 'my title post modified 2', comments: [{id: 25, comment: 'my comment for post id 1'}]},
      {`id: 8`, user_id: 2, title: 'my title post', comments: [{`id: 25`, comment: 'my comment for post id 1'}]},
    ]

示例如何显示,我只能修改数组的第一个和第二个对象,但不能修改第二个对象中的注释。

希望我正确地表达了自己。

标签: laravelapivalidation

解决方案


首先确保您以格式获取 Post 数据,并在键和字符串周围JSON加上双引号。"并在 Laravel - PHP 中创建 JSON 数据,例如:

$postsData = '[
  {"id": 1, "user_id": 1, "title": "my title post", "comments": [{"id": 5, "comment": "my comment for post id 1"}]},
  {"id": 2, "user_id": 1, "title": "my second title post", "comments": [{"id": 15, "comment": "my comment for post id 2"}]},
  {"id": 8, "user_id": 2, "title": "my third title post", "comments": [{"id": 25, "comment": "my comment for post id 8"}]}
]';

$posts = json_decode($postsData);

//var_dump($posts);

$authUserId = 1;

foreach($posts as $post) {
  if($authUserId == $post->user_id) {
      echo 'User own this Post...<br/>';
      echo $post->id.' - '.$post->title;
      foreach($post->comments as $comment) {
              echo '<br/>';
              echo '----'.$comment->id.' - '.$comment->comment;
              echo '<br/>';
      }
      echo '<br/>';
  }
}

输出将是用户 1 只能保存 Post 1 和 2:

User own this Post...
1 - my title post
----5 - my comment for post id 1

User own this Post...
2 - my second title post
----15 - my comment for post id 2

推荐阅读