2016-02-19 63 views
1

與Laravel 5.2和Laravel Collective一起工作。所以我有這個問題 - 我試圖用我的用戶的first_namelast_name進行下拉(選擇),但在我的用戶表first_namelast_name處於不同的行。我怎樣才能一起在一個下拉列表中顯示它們?從下拉列表中的一行中的兩行 - Laravel 5.2

這裏是我的控制器有:

'teachers'=>User::where('type','=','teacher')->lists('first_name', 'last_name','id'),

有了這個,我只看到first_name

並在視圖:

{!! Form::select('teacher_name', $teachers, null, ['class' => 'form-control']) !!}

表結構:

Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('username'); $table->string('password'); $table->string('first_name', 20); $table->string('last_name', 20); $table->integer('class_id') ->unsigned() ->nullable(); $table->enum('type', ['admin', 'teacher', 'student']); $table->rememberToken(); $table->timestamps();

人嗎?

+1

你的意思是first_name和last_name在不同的行中是什麼意思?你可以在這裏發佈你的表格結構嗎? – Donkarnash

+0

等待我將更新:) –

+0

好的,你只能看到first_name,因爲它的工作原理應該如此。當你在{!! Form :: select()!!}中傳遞$ teachers數組時,它會將它填充爲選擇選項的鍵值對。因此,如果您使用devtools檢查select元素,您將能夠看到每個選項的last_name值。例如:如果要顯示first_name last_name並希望該值爲用戶的id,則必須相應地在控制器中構建教師陣列 – Donkarnash

回答

1

屬性派上用場做這樣的事情的時候。在老師的模型,你可以把:

public function getFullNameAttribute() 
{ 
    return $this->first_name . ' ' . $this->last_name; 
} 

然後在你的控制器的說:

$teachers = Teacher::lists('full_name','id'); 

..和你的觀點將現在的工作,因爲它是。

+0

這是有效的,它真的鬼鬼祟祟!謝謝! :) –

+0

只是我在我的控制器應該是''teachers'=> User :: where('type','=','teacher') - > get() - > lists('full_name'), –

0

你可以嘗試這樣的:

$teachers = User::where('type', 'teacher')->get(); 
$teachersArray = []; 
foreach ($teachers as $teacher){ 
    $teachersArray[$teacher->id] = $teacher->first_name.' '.$teacher->last_name; 
} 

薪火$ teachersArray到您的視圖,並在您的形式:

{!! Form::select('teacher_name', $teachersArray, null, ['class' => 'form-control']) !!} 
+0

你可能需要在for循環 – Donkarnash

+0

Ups之外初始化$ teachersArray,我忘記了,謝謝。 – Tensho

相關問題