Laravel Eloquent Pluck without losing the key - php

I have the following collection in Laravel:
["TheNumbers":[{"episodeID":16818,"episodeNumber":100,"created_at":null,"updated_at":null},{"episodeID":16818,"episodeNumber":210,"created_at":"2017-02-20 21:30:38","updated_at":"2017-02-20 21:30:38"}]
If I run the following code:
$TheEpisode->TheNumbers->pluck('episodeNumber');
I will get the following result:
[100,210]
I would like to keep the keys for each number, how can I achieve this?
EDIT: EXPECTED RESULT:
This is my expected result:
[{"episodeNumber":100},{"episodeNumber":210}]
PHILIS PETERS (improved)
TheEpisode->TheNumbers->reduce(function ($result, $episode) {
$episodeData = (collect())->put('episodeNumber', $episode['episodeNumber']);
$result[] = $episodeData;
return $result;
}));

Pluck() can take two params. The second of which is what the value can be keyed by.
You should be able to do:
$TheEpisode->TheNumbers->pluck('episodeNumber', 'episodeID');
Hope this helps!

Try something like this, it should work using map...
return $TheEpisode->TheNumbers->map(function ($episode) {
return ['episodeNumber' => $episode['episodeNumber']];
});

This can be simply achieved by passing a second argument to pluck. From the documentation:
You may also specify how you wish the resulting collection to be
keyed:
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

$collection->forget(['created_at', 'updated_at]);
This will simply left two first key-value pairs. Worth to keep in mind:
forget does not return a new modified collection; it modifies the collection it is called on.
Laravel docs
This should work properly:
$collection->only(['episodeID', 'episodeNumber']);

Try using
$TheEpisode->TheNumbers->lists('episodeNumber');
the key will remain.

Try using mapWithKeys like this:
$TheEpisode->TheNumbers->mapWithKeys(function ($theNumber) {
return ['episodeNumber' => $theNumber['episodeNumber']
});
I assume you want the result like this:
"TheNumbers":['episodeNumber':100,'episodeNumber':210]

For sake of updated Laravel, I tried all and I found
return Model::get(['name','id'])
will give reduced results with key => value.

Related

How do i resolve Call to a member function only() on array error

I want to use laravels FormRequest to validate before updating some fields. This works fine if i just use:
User::find($application->userid)->fill($request->only('first_name'...
but the request also contains sub array ($request->programmeData).
array:2 [▼
"programme_id" => 5
"programme_title" => "some programme title"
]
if i try access that the same way i get 'Call to a member function only() on array':
Course::find($application->userid)->fill($request->programmeData->only('programme_id...
I've tried a handful of things, but not sure best way to go with this?
Update
I'm now using a foreach loop to save two items in the array. the example below saves the second value for both user_ids. any reason this isn't saving the first value for the first user_id?
foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->get()[$key]->fill(Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']))->save();
}
but nothing updates. Any ideas on this one?
You can use Array::only() helper for this:
foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->first()->fill([
$key => Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id'])
])->save();
// or
$course = Course::where('application_id', $application->id)->first()
$course->$key = Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']);
$course->save();
}
//Arr::only($request->programmeData, ['programme_id', ...]);

Laravel - pluck with specified keys

I have a line of code similar to the following:
Sport::pluck('id', 'name)
I am dealing with frontend JavaScript that expects a list in this format:
var list = [
{ text: 'Football', value: 1 },
{ text: 'Basketball', value: 2 },
{ text: 'Volleyball', value: 3 }
...
]
I am trying to figure out how I can somehow transform the id and name values that I pluck from my model to a format similar to the Javascript list.
If that's unclear, I am looking to end up with an associative array that contains two keys: text and value, where text represents the name field on my model, and where value represents the id of the model - I hope this makes sense.
How would I approach this?
I initially tried something like this (without checking the documentation)
Sport::pluck(["id" => "value", "name" => "text]);
But that isn't how you do it, which is quite clear now. I've also tried some map-related snippet, which I cannot seem to Ctrl-z to.
Any suggestions?
Another method is to use map->only():
Sport::all()->map->only('id', 'name');
The purpose of pluck is not what you intend to do,
Please have a look at below examples,
Sport::selectRaw("id as value, name as text")->pluck("text","value");
// ['1' => 'Football', '2'=>'BasketBall','3'=>'Volleyball',...]
Syntax
$plucked = $collection->pluck('name', 'product_id');
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
Please see the documentation.
Your output is possible using simple code.
Sport::selectRaw('id as value, name as text')->get();
You could use map.(https://laravel.com/docs/5.8/collections#method-map)
$mapped = Sport::all()->map(function($item, $index) {
return [
"id" => $item["id"],
"name" => $item["text"]
];
});
This is the easiest way. Actually Laravel offers a better way for it. You can use api resources to transform your data from eloquent for the frontend:
https://laravel.com/docs/5.8/eloquent-resources
Try with toArray function:
Sport::pluck('id', 'name)->toArray();
Then you can return your result with json_encode php function;

Convert multiple array into a string in laravel

$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->get(array('id'));
return $est_data;
result:
[{"id":43},{"id":71},{"id":41},{"id":39}]
This is my above laravel condition and result, i want the result to be like 43,71,41,39.
Can anyone please help me, how can be this done using php. i tried with implode() function, but getting error, please help...thank you
Laravel pluck method will select required fields only:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return $est_data;
As commented by #apokryfos for your laravel version (4.2) lists method should be used, so it is:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->lists('id');
return $est_data;
You can use the laravel array_flatten() array helper:
The array_flatten function flattens a multi-dimensional array into a
single level array:
$array = array('name' => 'Joe', 'languages' => array('PHP', 'Ruby'));
$array = array_flatten($array);
// array('Joe', 'PHP', 'Ruby');
In your case:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_flatten($est_data);
$result = implode(',',$est_data[0]);
This will solve your problem. You should read about implode(convert to string) and explode (string to array). They are really useful php functions.
Reading your comment, your error is coming from the fact that you try to access $set_data and not $set_data[0] where you values are based on the output you provided us.
Use the php array_column function, specifying the id:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_column("id", $est_data);

Laravel isset with array value

I am having an issue - well because the value I am trying to pull from the DB does not exist yet.
Is there away that I check if its isset?
Is there any better way that I can get my value from the db to save on double code?
Controller:
$siteSocialFacebook = socialSettings::where('socialName','=','facebook')->get();
$siteFacebook = $siteSocialFacebook[0]['socialLink'];
Blade:
value="{{ old('facebook', #$siteFacebook)}}"
If you will only ever expect one result, use first() instead of get() and skip the array. You can pass it into the Blade template like this:
return view('blade', [
'siteFacebook' => $siteSocialFacebook['socialLink'] ?: null,
]);
This will prevent any issues with undefined parameters.
Edit: I just realized you're treating models as arrays. You can do this too:
return view('blade', [
'siteFacebook' => $siteSocialFacebook->socialLink,
]);
That handles it for you.

Sorting a collection in doctrine2

I've written the following query (that may or may not be efficient, I'm still a newbie):
$collection = $this->dm->getConnection()->selectCollection('db_name', 'collection_name');
$query = array('array_name' => new \MongoId(id));
$cursor = $collection->find($query)->limit(9)->sort('r', 'desc');
I'm trying to sort by an r value that looks like this in the document:
"r": 0.58325652219355106354
but it isn't actually sorting it by that r-value. What am I doing wrong?
Pretty sure sort takes an array argument. Try
->sort(['r' => 'desc]);
I looked it up...
http://apigen.juzna.cz/doc/doctrine/mongodb/source-class-Doctrine.MongoDB.Cursor.html#564-585

Categories