Laravel pluck with map changes array keys - laravel

I have a problem with laravel pluck on a map function.Generally I take payments from database like this:
$payments = Payment::with('translation')->active()->get();
And result is:
Each payments has different translations so I use function to get proper ones. For that I've added map function to query to get translation like this:
$payments = Payment::with('translation')->active()->get()->map(function ($payment) {
return ['key' => $payment->getName() . ' +' . $payment->cost, 'value' => $payment->id];
})
->pluck('key', 'value')
->prepend('Choose payment...');
And result is:
Array keys are different from payment ones. It should be like 1,9,12 etc.
If I switch order of pluck for value then key result will be with right keys:
But after that blade forms from htmlcollective ({!! Form::select() !!}) will show keys as dropdown text, and translations as value. (like opposite).
Is there any simple way to fix that?

It was prepend causing keys to be wrong. Any prepend without specified key will be automaticaly added as 0 (zero), and all other keys will count from there.
To fix change:
->prepend('Any text here');
to:
->prepend('Any text here', '');
Key will be set as '', and other keys will be not changed:

Related

Passing multiple string as parameter through url in laravel to delete specific data from database

I want to delete multiple string data that is passed by url separated by ','.
Scenario is :
http://127.0.0.1:8888/remove/lui,kui
Through this route lui and kui data that is value of name field in database will be deleted.
My web.php file
Route::get("/remove/{name}",[MyController::class,"remove"]);
MyController.php file
use App\Models\City;
function remove($name){
}
Thanks,your suggestion will be helpful.
You can accomplish this with the following:
//The string of names
$names = "cat,cat,cat,mouse,dog,rabbit";
//We break it down, seperate them by comma, then add them to an array
//After we will get the unique values only of that array
$arrayOfNames = array_unique(explode(',', $names));
//search in the name column for any of these values
//delete if found
//note that you can change the word "name" to any other column name
City::whereIn('name', $arrayOfNames)->delete();
If you have the softdelete trait in your model, and would like to hard delete its: https://laravel.com/docs/9.x/eloquent#soft-deleting
//search in the name column for any of these values
//hard delete if found
City::whereIn('name', $arrayOfNames)->forceDelete();
You can also do an update as well if that is something you are interested in the future:
//search in the name column for any of these values
//update if found
City::whereIn('name', $arrayOfNames)->update(['age' => 123, 'updated_at' => now()]);
Hope it works well for you :)

Laravel Collection Filter breaking serialization format

I have a serialized String like this
$string = '[{"name":"FOO"},{"name":""},{"name":"BAR"}]';
I am trying to process it via Laravel Collection's filter method and eliminate items without a defined "name" property.
$collection = collect(\json_decode($string));
$collection = $collection->filter(function($v){
return !empty($v->name);
});
$string = \json_encode($collection->toArray());
dd($string);
Normally I am expecting something like this:
[{"name":"FOO"},{"name":"BAR"}]
But I'm getting something like this:
{"0":{"name":"FOO"},"2":{"name":"BAR"}}
Funny thing is, if I skip the filtering process or return true every time, I keep getting the string in the desired format. Removing the toArray() call has the same result. I don't want to keep the numeric indices as associative object keys.
Why this anomaly? And what should I do to get the serialized data in desired format?
In PHP arrays the index key must be unique.
In your case you have the key 'name' and collection automatically assigns the index key to all items in the collection.
To overcome that problem just call
$string = \json_encode($collection->values());

Laravel collections convert key value to key assoc array

I use this function: $assets->pluck('url').
It outputs: ['link','link1','link2']
How to convert it to: [{url: 'link'}, {url: 'link1'}, {url: 'link2'}]
You can add functions to the relation query to only return the url field. This way you will get the desired result.
$assets = auth()->user()->assets()->select('url')->get();
You can use the ->only() collection method to specify the fields you want to return:
$assets = auth()->user()
->assets
->only(['url'])
->all();
To return a collection of which contain only certain field on model you can add an array of list of fields to retrieve as parameters of the get method on your model
ModelName::get(['id', 'url']);
or by passing list of fields as paremter to the select method
ModelName::where([...])->select('id', 'url')->get();

Laravel 5.5, Collections and Localization

This question is a follow-up/attempt to implement the answer from a prior question.
My attempt to pluck values from a collection and apply the current localization is as follows:
$prefix_array = ['' => trans('registration.prefixes.select')] +
$prefixes->pluck('prefix', 'prefix')->map(function($item, $key) {
return trans('messages.fields.prefixes.'.$item);
})->toArray();
However, this produces an array with values like:
"Mrs." => "messages.fields.prefixes.Mrs."
Instead of:
"Mrs." => "Sra." // eg: shortened Senora for Spanish translation
The localization path (messages.fields.prefixes.XYZ) is correct and references to it in other places displays as expected.
It may be trailing dot (period) is confusing the localisation. You may need to have your translation key as just 'mrs' => 'Mrs.'

In backend: how to get checkboxed items id?

How I can get ids of checked items in items list in backend. I want add extra functionality to publish function. So what I need is to get that checked ids. In (com_registracijos\controllers\lists.php) I tried add something likes this:
function publish()
{
$id = JRequest::getInt('id');
$value = JRequest::getInt('value');
$boxchecked = JRequest::getInt('boxchecked');
}
To get the ids of a list checked itemsyou should get and array instead of an int:
$arrayIDs = JRequest::getVar ( 'cid', null, 'default', 'array' );
Please, note that cid is the name of the check.
Every component, if any, of the resulting array is a checked item id.
If you need a sample, you may check delete uploaded file from an array of id when they are delted in joomla? It is doing a delete, but it will give you the idea.
Regards,

Resources