Home > Enterprise >  Why i can just showed comments for odd post? is there any logic error? pls help to fix it
Why i can just showed comments for odd post? is there any logic error? pls help to fix it

Time:08-21

All. I'm facing a problem which is creating a post page like "FB" which consist of multiple post in a page. And I wrote a the controller function like this:

public function getPosts(Request $request){
        $user=User::all()->where('id',Auth::id()); //passing to input post in current.blade
        $users=User::all()->where('id',Auth::id()); //passing to data.blade which seperate file

        $posts=Content::with('comments')
        ->leftjoin('users','contents.UserID','=','users.id')
        ->leftjoin('content_attachments','contents.id','=','content_attachments.ContentID')
        ->select('contents.*','contents.id as pid','users.name','users.userAvatar','content_attachments.*')
        ->orderBy('contents.created_at', 'DESC')
        ->paginate(5);
    
        //ajax for infinite scroll
        if($request->ajax()){
            $view=view('data')->with('user',$user)->with('users',$users)->with('posts',$posts)->render();
            return response()->json(['html'=>$view]);
        }
        // dd($posts);
        return view('community')->with('user',$user)->with('users',$users)->with('posts',$posts);
    }

But the result is 1st post has comment showed 2nd post cannot display comment (no array passing) 3rd post has comment showed (but its for 2nd post) 4th post cannot display comment (no array passing) 5th post has comment showed (but its comment for 3rd post) Output: post view

Comment model:

    public function content(){
        return $this->belongsTo('App\Models\Content');
    }
    
    public function user(){
        return $this->belongsTo('App\Models\User');
    }

Content Model(post):

    public function users(){
        return $this->belongsTo('App\Models\User');
    }

    public function contentAttachment(){
        return $this->hasMany('App\Models\ContentAttachment')->withTimestamps();
    }

    public function comments(){
        return $this->hasMany('App\Models\Comment');
    }

User Model:

    public function comment(){
        return $this->hasMany('App\Models\Comment');
    }

    public function content(){
        return $this->hasMany('App\Models\Content');
    }

data.blade: which specific for post passing

@foreach($users as $users)
   @foreach($posts as $post)
      <li>
         <!-- begin timeline-time -->
            <div >
               <input type="hidden" id="postID" value="{{$post->pid}}">
               <span  id="date{{$post->pid}}">{{ \Carbon\Carbon::parse($post->ctDate)->format('d F') }}</span>
               <span >{{$post->ctTime}}</span>
            <!-- </a> -->
            </div>
            <!-- end timeline-time -->
            <!-- begin timeline-icon -->
            <div >
               <a href="javascript:;">&nbsp;</a>
            </div>
            <!-- end timeline-icon -->
            <!-- begin timeline-body -->

            
            <div >
               <div >
                  <span ><img src="{{ asset('images/user/'.$post->userAvatar) }}" alt=""></span>
                  <span ><a href="javascript:;">{{$post->name}}</a> <small></small></span>
                  <span >18k Views</span>
                  @if(Auth::id() == $post->UserID)
                  <div >
                     <!-- EDIT -->
                     <span  style='font-size:10px' id="navbarDropdownMenuLink">
                        <a href="javascript:editPost({{$post->pid}});"  style='padding:5px 13px;' data-mdb-toggle="modal" data-mdb-target="#editModal" data-target-detail="{{$post->ctDetail}}" data-target-pid="{{$post->pid}}" data-target-pic="{{ asset('images/post/image/'.$post->ctImage) }}">
                           <i class='fa fa-pen' style='color:whitesmoke;'></i>
                        </a>
                     </span>
                     <!-- DELETE -->
                     <span  style='font-size:10px' id="navbarDropdownMenuLink" >
                        <a href="{{route('delPost',['id'=>$post->pid])}}"  style='padding:5px 13px;' onclick="return confirm('Are you sure to delete this post?')">
                           <i class='fa fa-trash' style='color:whitesmoke;'></i>
                        </a>
                     </span>
                  </div>
                  @endif
               </div>
               
               <div >
                  <p  id="postBody{{$post->pid}}"> <!--  -->
                     {{$post->ctDetail}}
                  </p>
                  <!-- ----------------------------------------IMAGE------------------------------------------------- -->
                  @if($post->ctImage!=NULL)
                     <img  id="image{{$post->pid}}" src="{{ asset('images/post/image/'.$post->ctImage) }}" alt="{{$post->ctImage}}" onclick="showImage({{$post->id}})">
                  @endif
                  <!-- ----------------------------------------VIDEO------------------------------------------------- -->
                  @if($post->ctVideo!=NULL)
                  <div >
                     <iframe id="iF{{$post->pid}}"  src="{{ asset('images/post/video/'.$post->ctVideo) }}" title="video" frameborder="0"  allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" width="auto" height="auto" sandbox="" allowfullscreen></iframe>
                  </div>
                  @endif
               </div>
               <div >
                  <div >
                     <!-- <span >259 Shares</span> -->
                     <!-- <span >0 Comments</span> -->
                  </div>
                  <div >
                        <span >
                        <i ></i>
                        <i ></i>
                        </span>
                     <span  id="stats-total-{{$post->pid}}">
                     @if($post->likedUsers->count() !=0)
                        {{$post->likedUsers->count()  rand(50,99)}}
                     @else
                        {{rand(50,99)}}
                     @endif
                     </span>
                  </div>
               </div>
               <div >
                  <!-- LIKE FUNCTION -->
                  @guest
                     <a href="#" ><i ></i> Like</a>
                  @else
                  <div >
                     <a href="javascript:;"  id="like-btn{{$post->pid}}" data-id="{{$post->pid}}" data-token="{{ csrf_token() }}" data-button="like-{{$post->pid}}" data-btnword="like-word-{{$post->pid}}" data-stats="stats-total-{{$post->pid}}">
                     <i  style="color:{{Auth::user()->likedPosts()->where('content_id', $post->pid)->count() > 0 ? '#02eb0d' : ''}}" id="like-{{$post->pid}}"></i>
                     <h3 style="display: inline-block;font-size:16px;color:{{Auth::user()->likedPosts()->where('content_id', $post->pid)->count() > 0 ? '#02eb0d' : ''}}" id="like-word-{{$post->pid}}">Like</h3></a>
                     <form action="{{route('post.like',$post->pid)}}" method="POST" style="display:none" id="like-form-{{$post->pid}}">@csrf</form>
                  </div>
                  @endguest

                  <!-- pop COMMENT FUNCTION -->
                  <a href="javascript:commentBox({{$post->pid}});" ><i ></i> Comment</a> 
                  <!-- SHARE FUNCTION -->
                  <div >
                     <div  data-id="{{$users->id}}" data-token="{{ csrf_token() }}">
                        <a href="https://www.facebook.com/sharer/sharer.php?u=http://127.0.0.1:8000/community" target="_blank"><div ><img src="Images/icons/facebook.png" alt=""><p>Facebook</p></div></a>
                        <a href="https://twitter.com/intent/tweet?url=http://127.0.0.1:8000/community" target="_blank"><div ><img src="Images/icons/twitter.png" alt=""><p>Twitter</p></div></a>
                        <a href="http://www.linkedin.com/shareArticle?mini=true&url=http://127.0.0.1:8000/community&title=Share title&summary=There will be a window left" target="_blank"><div ><img src="Images/icons/linkedin.png" alt=""><p>LinkedIn</p></div></a>
                        <a href="https://wa.me/?text=http://jorenvanhocht.be" target="_blank"><div ><img src="Images/icons/whatsapp.png" alt=""><p>WhatsApp</p></div></a>
                     </div>
                     <a ><i ></i> Share</a>
                  </div>
               </div>
               <!-- COMMENT SHOW-->
               <div  id="comment{{$post->pid}}" style="display: none;">
                  @foreach($post->comments as $comment)
                  <div >
                     @if($comment->UserID == 1)   
                     <div ><img src="{{ asset('images/user/ghost.jpg') }}"></div>
                     <span >George</span>
                     @elseif($comment->UserID ==2)
                     <div ><img src="{{ asset('images/user/guest1.png') }}"></div>
                     <span >Ved</span>
                     @else
                     <div ><img src="{{ asset('images/user/user.jpg') }}"></div>
                     <span >David Lee</span>
                     @endif
                     <div >
                        <p>{{$comment->cmDetail}}</p>
                     </div>
                     @if(Auth::id() == $comment->UserID)
                     <div >
                        <!-- DELETE -->
                        <span  style='font-size:10px' id="navbarDropdownMenuLink" >
                           <a href="{{route('delComment',['id'=>$comment->id])}}"  style='padding:6px 13px;' onclick="return confirm('Are you sure to delete this comment?')">
                              <i class='fa fa-trash' style='color:whitesmoke;'></i>
                           </a>
                        </span>
                     </div>
                  @endif
                  </div>
                  @endforeach
                  <!-- ADD COMMENT  -->
                  <div ><img src="{{ asset('images/user/'.$users->userAvatar) }}"></div>
                  <div >
                     <form action="{{route('addComment')}}" method="POST" id="comForm" enctype="multipart/form-data">
                        @CSRF
                        <div >
                           <input type="hidden" name="userId" id="userId" value="{{$users->id}}">
                           <input type="hidden" name="postId" id="postId" value="{{$post->pid}}">
                           <input maxlength="200" type="text" name="comment" id="comment"  autocomplete="off" placeholder="Write a comment..." required/>
                           <span >
                           <button  type="submit" data-id="{{$users->id}}">Comment</button>
                           </span>
                        </div>
                     </form>
                  </div>
               </div>
            </div>
         <!-- end timeline-body -->
      </li>
   @endforeach
@endforeach

Comments table in phpmyadmin: comment db

Contents table in phpmyadmin: content db

CodePudding user response:

instead you can do like this

$posts = Content::with('comments.user')
->orderBy('created_at', 'DESC')
->paginate(5);

as a result your comments are contained within each post object. it is much easier to loop over posts with a query like this

  • Related