M
M
Maxim2020-04-17 12:46:44
Laravel
Maxim, 2020-04-17 12:46:44

How to load comments in Laravel ajax?

How to load comments via ajax?

I send a request and form comments, but how to return the comments themselves and, for example, the countComments field, so that the controller returns, for example, like this

comments: {},
total,
...


public function more(Request $request,$content,$type,$tale){
        if ($request->ajax()){
            $query = Comment::where('content_id', $content)->where('type', '=', $type)->where('parent','=',0)->orderBy('id', 'desc')->skip($tale);
            $comments = $query->take(2)->get();
            $countComments = $query->get()->count(); //Всего комментариев

            foreach ($comments as $comment) {
                $moreChildrens = 0; //Всего дочерних комментариев
                $getChildrens = 6; //По сколько подгружаем
                $queryChildrens = Comment::where('parent','=', $comment->id);
                $childrens = $queryChildrens->take(6)->get();
                $count = $queryChildrens->count();
                if ($count <= 6){ //Если количество оставшихся комментариев меньше либо равно общему количеству
                    $moreChildrens = 0;
                    $getChildrens = 0;
                }else{
                    $moreChildrens = $count - 6; //Присваем переменной количество оставшихся комментариев
                    if ($moreChildrens <= $getChildrens) $getChildrens = $moreChildrens; //Запись вида - показать $getChildrens из $moreChildrens
                }
                $comment->childrens = $childrens;
                $comment->more_childrens = $moreChildrens;
                $comment->get_childrens = $getChildrens;

            }
            
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-04-17
@Aslero

return CommentResource::collection($comments);
total included, taken from here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question