0

Using Eloquent, I want to remove 2 objects from the $outputs array with 'Title' B and keep only one.

$outputs has the following information:

[
    {
        "Title": "A",
        "Publication date": "2013",
    },
    {
        "Title": "B",
        "Publication date": "2010",
    },
    {
        "Title": "B",
        "Publication date": "2999",
    },
    {
        "Title": "B",
        "Publication date": "5555",
    },
];

I know there are plenty of posts about this but I couldn't find a way to do it myself. Any help will be appreciated.

2
  • 2
    Please post your query here. Commented Jun 26, 2019 at 0:40
  • Just made the question a bit clearer to understand. Adding some code would be a good idea @João Domingues Commented Jun 26, 2019 at 13:34

2 Answers 2

1

If this is for an array/collection, and not an Eloquent query, you can use the collection keyBy method to get unique values.

https://laravel.com/docs/5.8/collections#method-keyby

$data = [
    [
        "Title" => "A",
        "Publication date" => "2013",
    ],
    [
        "Title" => "B",
        "Publication date" => "2010",
    ],
    [
        "Title" => "B",
        "Publication date" => "2999",
    ],
    [
        "Title" => "B",
        "Publication date" => "5555",
    ],
];

$collection = collect($data)->keyBy('Title');

Then your output will look like this:

Collection {#1389 
  #items: array:2 [
    "A" => array:2 [
      "Title" => "A"
      "Publication date" => "2013"
    ]
    "B" => array:2 [
      "Title" => "B"
      "Publication date" => "5555"
    ]
  ]
}

The keyBy method will give you the last item in the collection for each Title, so you can sort the collection before calling keyBy if you want to get specific items:

// get each Title with the highest Publication date
$collection = collect($data)->sortBy('Publication date')->keyBy('Title');

// get each Title with the lowest Publication date
$collection = collect($data)->sortByDesc('Publication date')->keyBy('Title');

If you want to get back an array without the keys "A" and "B" then you can do this:

$collection = collect($data)->keyBy('Title')->values()->toArray();

Output:

array:2 [
  0 => array:2 [
    "Title" => "A"
    "Publication date" => "2013"
  ]
  1 => array:2 [
    "Title" => "B"
    "Publication date" => "5555"
  ]
]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was doing crazy loops trying to remove / push , tried everything. Only 1 line of code does all the thing lol thank you.
0

You can do this by using destinct and groupBy in your query.

1 Comment

this is an array i've built couldn't use distinct because data is coming from different sources

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.