laravel - 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'}]},
]
示例如何显示,我只能修改数组的第一个和第二个对象,但不能修改第二个对象中的注释。
希望我正确地表达了自己。
解决方案
首先确保您以格式获取 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
推荐阅读
- windows - 我需要安排一个作业在 Windows 2016 上启动时运行一次而无需用户登录
- scala - 在 Spark 中读取 CSV 文件时出错 - Scala
- java - 让我跳入平台游戏的代码也破坏了我的碰撞代码
- javascript - TypeError:无法读取 Plotly.js 上未定义的属性“地图”
- node.js - TestCafe:将另一个文件中的测试导入当前的夹具
- php - 使用返回 null 的 curl 解析 XML
- python - 尝试在 pycharm 上创建新变量时出现“未解决的参考”
- opengl-es - glBufferSubData 在许多 android 设备上非常慢
- anylogic - 将潮汐时间融入 AnyLogic
- mongodb - findByIdAndUpdate 返回 200 响应但不更新