Search code examples
phpjsonlaravellaravel-collection

Filtering with Laravel


In my Laravel project I have the following problem. (I have reduced the output a little for easier readability)

  1. I fetch all the posts from a table named Newsposts. I store this as a collection called $all_posts, which looks like this:
Collection {#216 ▼
  #items: array:7 [▼
    0 => NewsPost {#227 ▶}
    1 => NewsPost {#228 ▶}
    2 => NewsPost {#229 ▼
      #attributes: array:6 [▼
        "id" => 6
        "title" => "Sample title"
        "body" => "<p>Some html</p>"
        "user_id" => 15
      ]
      #original: array:6 [▶]
      #casts: []
      .
      .
      #guarded: array:1 [▶]
    }
    3 => NewsPost {#230 ▶}
    4 => NewsPost {#231 ▶}
  ]
}
  1. I then fetch all entries from another table called user_read witch contains all the posts the current user have read. This table contains a reference to the user with a 'user_id'-column, and a reference to the newsposts with a 'post_id'-column. I also store this in a collection, which looks like this:
Collection {#219 ▼
  #items: array:2 [▼
    0 => UserRead {#210 ▼
      #attributes: array:4 [▼
        "user_id" => 15
        "post_id" => 6
      ]
      #original: array:4 [▶]
      #casts: []
      .
      .
      #guarded: array:1 [▶]
    }
    1 => UserRead {#217 ▶}
  ]
}
  1. So what I want to do now is take the $all_posts-collection and remove all the posts from $read_posts-collection, and store it in a new collection. Lets call it $unread_posts. How can i achieve this?

Solution

  • get all readed post id first, then use filter function to filter unread posts

    $readedPosts = $user_read->pluck('post_id');
    $unread_posts = $all_posts->filter(function($value) use ($readedPosts) {
          return !in_array($value->id, $readedPosts);  
    })