lundi 23 juillet 2018

How to remove Model instance from Collection

I have a Collection of Articles, like so (the query is simplified for clarity):

$articles = Article::all();

And I have an Article:

$a = Article::find($id);

How can I remove $a from $articles? Note that $a should always exist in $articles.

I tried:

$filtered_articles = $articles->map(function ($current, $key) use ($a)
{
  if ($current->id != $a->id) {
    return $current;
  }
});

However, this returns a Collection with 'null' in the place $a used to be, example:

Collection {#220
  #items: array:8 [
  0 => Article {#243}
  1 => null
  2 => Article {#245}
  3 => Article {#246}
  4 => Article {#247}
  5 => Article {#248}
  6 => Article {#249}
  7 => Article {#250}
]}

This, of course, breaks functionality on other parts of my site. I'd like to get that exact collection, but without the null entry.
What would be the most painless way of dealing with this problem?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire