skip to Main Content

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

3

Answers


  1. 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'
    );
    
    Login or Signup to reply.
  2. 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']
    ) }}
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search