Last active
May 11, 2020 00:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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