Get count posts of model Post Laravel

27
February 11, 2019, at 2:20 PM

I have a model Post, in this model I created accesor:

protected $appends = ['post_count']; 
public function getPostCountAttribute() {
   return $this->count();
}

When I want to show a post_count in blade:

$post->post_count;

I get error: Undefined property: Illuminate\Pagination\LengthAwarePaginator::$post_count

Why I get this error? And how I can fix it?

In controller:

public function allPosts() {
    $posts = Post::active()->paginate(15);
    return view('posts', compact('posts'));
}

In blade:

{{ $posts->post_count }}
@foreach($posts as $post)
    {{ $post->title }}
@endforeach
Answer 1

It feels like you want to display the count of Posts in your view. This is not a good case to use an accessor. You would typically use an accessor to modify the attributes of a single Post.

Do this instead:

public function allPosts() 
{    
    $posts = Post::active()->paginate(15);
    return view('posts', compact('posts'));
}

... and then in your blade

{{ $posts->total() }}
@foreach($posts as $post)
    {{ $post->title }}
@endforeach
Answer 2

You are doing wrong. post_count will only work in foreach loop for every model. To count all post you could do like this $posts->count()

Count

READ ALSO
How can i use dropdown in table <td> tag

How can i use dropdown in table <td> tag

I have an Inline editable Table which updates the Mysql table for the team group column I want to use the drop-down list

35
Devilbox laravel register page throws 502 but works after refresh

Devilbox laravel register page throws 502 but works after refresh

I have setup laravel on devilbox and I'm creating my first application using this tutorial: https://auth0com/blog/creating-your-first-laravel-app-and-adding-authentication/

28
How to save in multiple tables Laravel

How to save in multiple tables Laravel

I want to do insertData in both tables together using the Query Builder in the Laravel 57 framework

11