lundi 30 juillet 2018

PHP Laravel | Testing Polymorphic Many To Many | If Statement not working correctly

So I'm not having a huge problem but I did notice something that did not work and I can't explain why. The issue is within the route as I'm just learning and messing around with Polymorphic Relations and what not.

Keep in mind all data is seeded and I have verified there is proper data in the fields by manually inserting comments and making sure the show up.

Here's my web.php file.

Route::get('/get/{id}/post', function($id) {
  $user = User::findOrFail($id);
  foreach($user->posts as $post) {
    echo "<hr /><h2>" . $post->title . "</h2>";
    echo "<p>By: ". $post->users->name ." | Date:" . $post->created_at->format('n-j-Y');
    echo "<br />" . $post->content . "</p><hr />";
    echo "<h3>Comments</h3>";
    if(!empty($post->comments)) {
      foreach($post->comments as $comment) {
        echo "<u>" . $comment->users->name . "</u><br />" . $comment->content . "<br /><br />";
      }
    } else {
      echo "Sorry there are no comments yet.";
    }
  }
});

The Problem I'm having is within the if statement at the bottom it does in fact pull all the comments and the Users name when comments exist. The real problem is that when there are no comments its not showing the else statement echo.

I find this really weird become I come to find it works if I'm just outputting one single post but not if I pull multiple post for that user.

Any Ideas why this would do this I'm really confused. Thanks!

Aucun commentaire:

Enregistrer un commentaire