首页 > 解决方案 > 如何在 Laravel 7 中同时使用下拉选择字段的 ID 和名称?

问题描述

我正在使用 Laravel 7 并且对它很陌生。我正在制作一个注册表单,它有一个下拉选择字段,用户将在其中选择一个选项。它运行良好,但我想将该选择框的名称值用作我在数据库表中的列之一。目前我可以使用用户选择的值的 id,但我也想使用名称。请帮忙。

在我的注册控制器中:

$categories = Category::all();
 
 $project = Project::create([
            'description'       => $request->description,
            'start_date'        => $request->start_date,
            'client_region'     => $request->region,
            'client_category'   => $request->category_id,
        ]);

在我的注册视图中:

<label for="category">Category</label><span class="text-danger">*</span>
<select class="custom-select" id="category_id" name="category_id">
   @foreach($categories as $category )
   <option value="{{ $category->id }}">{{ $category->name }}</option>
   @endforeach
</select>

如何在刀片视图中显示 ID:

// This will display an Integer value e.g 1
<p><span>{{ $project->category_id }}</span>

我想显示用户选择的选项的名称,例如:

 <p><span>{{ $project->category_name }}</span>

//This should display a string value e.g Category One, Category Two e.t.c

标签: laravel

解决方案


推荐阅读