DudeOfLayers
DudeOfLayers

Reputation: 130

Laravel: How to get an array of existing ids from a column, where later on will use `whereIn`

consider the following function:

public function index($countryCode, Request $request) {
    $invalidCountryTranslations = $countriesTranslation->whereIn('LanguageID', $arrayOfExistingIds)->get();
    return view('admin.countriesTranslations.create', compact('countryCode', 'languages', 'countriesTranslation'));
}

I am using the above function to find out which countries are already in the table (so it wouldn't be called into the view) so basically $arrayOfExistingIds should hold those existing rows from LanguageID column.

so the question is, how do I get the existing arrays of a LanguageID column?

$arrayOfExistingIds = ???

Upvotes: 1

Views: 163

Answers (2)

therealbigpepe
therealbigpepe

Reputation: 1549

As Alexey told you, use pluck() method, it will retrieve a collection, if you want an array concatenate it with toArray() or with all() methods, just like this;

Model::take(5)->pluck("id")->toArray();
Model::take(5)->pluck("id")->all();

This will give you your desired array. Try to not to use the lists() method because it is has been deprecated in 5.2.0.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163818

Use the pluck() method.

The pluck method retrieves all of the values for a given key

Model::pluck('id');

Upvotes: 1

Related Questions