2
votes

Sorry for such a stupid question but im on deadend right now, Im working on a personal project using Laravel (first time btw) and i ran into some problem.

I tried to do {{ $kategori->post()->count() }} (this is works btw) but with Users table. I already set the foreign key and stuff.

I tried to modify the User.php too (See code) but still didnt work as i intended. I need some helps. And im using the Laravel "php artisan make:auth"

I've tried edited the Model (User.php and Post.php) and Controller but i still cant figure out whats wrong.

Post.php

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}

User.php

public function post()
{
   return $this->hasMany('App\Post','user_id');
}

Controller

use App\User;

// other methods in the Controller

public function index()
{
   $posts = post::paginate(5);
   $user = User::post;
   return view('index', compact('posts', 'user'));   
}

blade view

{{ $user->post()->count() }}
2

2 Answers

1
votes

I did not understand the main purpose of the source code But you can use following code to count relation

$user_post_count = User::find($id)->post()->count();
$all_user_with_post = User::all()->with('post');
$all_user_with_post_count = User::all()->withCount('post');
1
votes

You're calling a post model that do not exist in this line:

$user = User::post;

This should be ::Post.

If you just want to count the number of posts you should use the withCount() method, this will count the number of posts without loading them, which will give you some perfomance.

$user = User::find($id)->withCount('post'); // this will count the number of posts to the given user.
return view('index', compact('user'));   

You can access the count this way in your view:

{{$user->post_count}}

You could also count the number of posts of all users:

$users = User::all()->withCount('post');

And do a foreach loop to access each one of them:

@foreach($users as $user)
{{$user->post_count}}
@endforeach

Docs:

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.

Note: you should name your relation posts, and not post, since its a one to many relationship.