我需要用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'}]},
]
示例显示,我只能修改数组的第一个和第二个对象,但不能修改第二个中的注释。
希望我表达得正确。
首先确保以JSON
格式获取Post数据,并在键和字符串周围使用双引号"
。并在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和Post 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