Level 33
Try this:
Post::count();
May Sale! All accounts are 40% off this week.
Hi, i am creating posts by json data. with single request i am able to create 5-10 posts, and i like to count and flash how many posts are created. I use the code below :
public function createPosts() {
..................
$data = json_decode($res->getBody(), true);
foreach ($data as $value) {
$post = Post::firstOrNew(['post_id' => $value['id']]);
$affected = $post->save();
}
$count = isset($affected) ? count($affected) : '0';
session()->flash('message', $count . ' Posts Created!');
return redirect('/home');
}
but i always receive 1 posts created, actually 10 post created. Do you have any idea, how i can count total posts created? Thanks in advence..
The reason you're always receiving 1 created is because you're reassigning your $affected variable each time you loop the data.
You'd need to do something like this which will increase the count every time you save a post.
$data = json_decode($res->getBody(), true);
// set the default affected count to zero
$affected = 0;
foreach ($data as $value)
{
$post = Post::firstOrNew(['post_id' => $value['id']]);
$post->save();
// increase the affected count
$affected++;
}
$count = isset($affected) ? count($affected) : '0';
session()->flash('message', $count . ' Posts Created!');
Please or to participate in this conversation.