API验证laravel 5.7

时间:2018-12-15 04:26:13

标签: laravel api validation

我需要使用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的用户是每个对象的所有者?帖子示例:

POST进行更新。



    [
      {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'}]},
    ]

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

希望我已经正确表达了自己。

1 个答案:

答案 0 :(得分:1)

首先请确保您以public getDataAsXLSX(list: Array<any>) { return this.http.get(this.url, { headers: this.headers, responseType: 'blob' as 'json' }); } 格式获取Post数据,并在关键字和字符串周围加上双引号JSON。并在Laravel-PHP中创建JSON数据:

"

输出将是只能为用户1保存帖子1和2:

$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/>';
  }
}