Curtis
Curtis

Reputation: 2704

Cleaner way to do select field in Laravel

Currently in my controller I've got the following:

public function create(Request $request)
{
    $categories = Categories::all();
    $list = [];
    foreach ($categories as $category) {
        $list[] = [
            $category->id => $category->name
        ];
    }

    return view('frontend.user.project', [
        'categories' => $list
    ]);
}

This is so I can populate my form using the html() helper, here's what I've got inside my view:

<div class="row">
    <div class="col">
        <div class="form-group">
            {{ html()->label(__('validation.attributes.frontend.category'))->for('category') }}

            {{ html()->select('category', $categories)->class('form-control') }}
        </div><!--form-group-->
    </div><!--col-->
</div><!--row-->

What's an easier/cleaner approach instead of creating another array?

Upvotes: 2

Views: 70

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

You can use pluck to avoid any loop:

public function create(Request $request)
{
    return view('frontend.user.project', [
        'categories' => Categories::pluck('name', 'id')->toArray()
    ]);
}

Upvotes: 4

Christophe Hubert
Christophe Hubert

Reputation: 2951

You can use the pluck() function:

    $lists = Categories::pluck('name','id');

Upvotes: 0

Related Questions