B
B
bpGusar2017-08-08 15:07:20
Laravel
bpGusar, 2017-08-08 15:07:20

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'));
    }

$user displays data about the user, $userPosts about the number of posts
in the view did this
@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

but the display of the number of posts does not work, how to do it right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
pantagruel964, 2017-08-08
@pantagruel964

// Model
public function posts()
{
    return $this->hasMany(Post::class);
}

// Controller
$users = User::withCount('posts')->get();

// View
@foreach ($users as $user)
    {{ $user->posts_count }}
@endforeach

If religion allows, you can read about it in the documentation

A
ajaxtelamonid, 2017-08-08
@ajaxtelamonid

1. Почему join ? Почему бы не сделать через eloquent ? Это же проще и читаемее будет.
2. Смотрите, вы перебираете $users и в качестве количества постов каждый раз подставляете одно и то же число $userPosts.

Евгений, 2017-08-08
@Flashter

судя по строчке

return view('admin.users.allusers', compact( 'user', 'userPosts'));
переменная $userPosts должна была уйти в массив. Могу предположить, что количество у вас сейчас по адресу $u->userPosts

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question