Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

closer01's avatar

how to count how many posts created?

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..

0 likes
3 replies
joedawson's avatar
Level 18

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!');
2 likes

Please or to participate in this conversation.