Answer the question
In order to leave comments, you need to log in
How to display the number of posts a user has?
Wrote code:
public function index()
{
$user = DB::table('users')
->leftJoin('users_group', 'users.id_user_group', '=', 'users_group.id_user_group')
->orderby('created_at','asc')
->paginate(10);
$userPosts = DB::table('users')
->Join('posts', 'users.id', '=', 'posts.id_user')
->where('posts.id_user', '=', 'users.id')
->count();
return view('admin.users.allusers', compact( 'user', 'userPosts'));
}
@foreach($user as $u)
<tr>
<th scope="row">{{$u->id}}</th>
<th><img src="{{ asset('img/avatars/' . $u->avatar)}}" class="rounded img-fluid" style="width: 35px;"/></th>
<td><a target="_blank" href="{{URL::to('user/' . $u->id)}}" class="card-link">{{$u->name}}</a></td>
<td>{{$u->group_name}}</td>
<td>{{$userPosts}}</td> //тут вывод количества постов
<td>{{ Carbon\Carbon::parse($u->created_at)->format('d.m.Y') }}</td>
<td><div class="btn-group">
<button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Действие
</button>
<div class="dropdown-menu">
<a href="{{URL::to('admin/users/' . $u->id . '/edit')}}" class="dropdown-item"><i class="fa fa-pencil" aria-hidden="true"></i>Редактировать</a>
{!! Form::open(['method' => 'DELETE','route' => ['p.destroy', $u->id]]) !!}
{!! Form::submit('Удалить',['class'=>'dropdown-item']) !!}
{!! Form::close() !!}
</div>
</div></td>
</tr>
@endforeach
Answer the question
In order to leave comments, you need to log in
// Model
public function posts()
{
return $this->hasMany(Post::class);
}
// Controller
$users = User::withCount('posts')->get();
// View
@foreach ($users as $user)
{{ $user->posts_count }}
@endforeach
1. Почему join ? Почему бы не сделать через eloquent ? Это же проще и читаемее будет.
2. Смотрите, вы перебираете $users и в качестве количества постов каждый раз подставляете одно и то же число $userPosts.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question