Reputation: 75
I need make an api with laravel 5.7, the api is not a problem itself.
I need make a strict validation for the current model and nested relations objects for save, example.
Imagine a model Posts with a relation comments. I have stored my data in database as:
[
{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'}]}
]
My user_id logged in the api is 1
If I try send a POST http
to update a post and a comment how I can validate the user logged in the api
is the owner of each object? example of post:
POST to update.
[
{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'}]},
]
how example show, I can modify only the first and second object of my array but I can't modify the comment in the second object.
hope I have expressed myself correctly.
Upvotes: 1
Views: 136
Reputation: 5180
First make sure you get your Post data in JSON
format, with double quotes "
surrounding keys and Strings. And Create JSON data in Laravel - PHP like :
$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/>';
}
}
Output will be that only Post 1 and 2 can be saved for User 1 :
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
Upvotes: 1