Home > Net >  How to display only specific data from an array in an input with Form::Select in Laravel?
How to display only specific data from an array in an input with Form::Select in Laravel?

Time:11-19

I have this array ( I displayed it with function dd() ), with multiple data, and I want to display only "name" data in input field.

enter image description here

That's how is looking now

enter image description here

And how I want to be displayed names.

enter image description here

That's my function from Controller that I push data to page.

 private function needs()
    {
        $grades = Grade::all()->pluck('name', 'id')->toArray();

        $subjects = Subject::all()->pluck('name', 'id')->toArray();

        $students = User::students()->get()->pluck('name', 'id')->toArray();

        $teachers = User::teachers()->get()->pluck('name', 'id')->toArray();

        $goals = Goal::all()->pluck('name', 'id')->toArray();

        $statuses = Status::all()->pluck('name', 'id')->toArray();

        $formats = Format::all()->map->only(['id', 'name', 'students'])->values()->toArray();

        return compact('grades', 'subjects', 'students', 'teachers', 'goals', 'statuses', 'formats');
    }

And there is form from the page :

<div >
                {{ Form::label('format_id', 'Формат', ['class' => 'col-sm-3 control-label no-padding-right']) }}
                <div >
                    {{ Form::select('format_id', [null => '--не выбран--']   $formats, $data->format_id ?? 0, ['class' => 'form-control', 'id' => 'format_id']) }}
                </div>
            </div>

CodePudding user response:

You can handle this with a little loop under the $format variable in your controller:

$arr = [];
foreach ($formats as $item) {
    array_push($arr, $item['name']);
}
$formats = $arr;

Or change this line like this:

$formats = array_column(
    Format::all()->map->only(['id', 'name', 'students'])->values()->toArray(),
    'name'
);

CodePudding user response:

You need to transform your $formats array to have key "id" and value "name":

{{ Form::select(
    'format_id',
    [null => '--не выбран--']   array_combine(array_column($formats, 'id'), array_column($formats, 'name')),
    $data->format_id ?? 0,
    ['class' => 'form-control', 'id' => 'format_id']
) }}

CodePudding user response:

You can use mapWithKeys() collection function to do so.

Exemple with formating an array to [id => name]:

$grades = Grade::all()->pluck('name', 'id')
            ->mapWithKeys(function ($grade) {
                return [$grade->id => $grade->name];
            })
            ->toArray();

// Or select instead of pluck
$grades = Grade::select('id', 'name')->get()
            ->mapWithKeys(function ($grade) {
                return [$grade->id => $grade->name];
            })
            ->toArray();

Documentation: https://laravel.com/docs/9.x/collections#method-mapwithkeys

  • Related