Skip to content

Instantly share code, notes, and snippets.

@leandroruel
Last active May 11, 2020 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandroruel/2fccf8e7f0645645c5c55b1057eea0a5 to your computer and use it in GitHub Desktop.
Save leandroruel/2fccf8e7f0645645c5c55b1057eea0a5 to your computer and use it in GitHub Desktop.
trait that uses eloquent to convert any array to select2 plugin data source: https://select2.org/data-sources/formats
<?php
namespace App\Traits;
trait Select2Formatter
{
/**
* Format your array to the format used by select2 plugin using eloquent
*
* @param array $data
* @param string $text
* @param array $selectedIds
*/
public function formatToSelect2DataSource(array $data, string $text, array $selectedIds = [])
{
$collection = collect($data);
$source = $collection->map(function ($value) use ($text, $selectedIds) {
$is_selected = in_array($value['id'], $selectedIds);
return [
'id' => $value['id'],
'text' => $value[$text],
'selected' => $is_selected
];
});
return response()->json([
'results' => $source
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment