任何人都可以幫助我解決這個問題嗎?我一直堅持幾天的錯誤htmlspecialchars()期望參數1是字符串,在Laravel 5.3中給出的數組爲。從Laravel 5.3的外鍵填充下拉的正確方法
這裏是我的控制器
public function create()
{
$categories = DB::table('categories')->pluck('name', 'id');
foreach($categories as $category)
{
echo $category;
}
return view('admin.processor.create', compact('categories', $categories));
}
這是我的看法(形式)
{!! Form::open(['url' => '/processor']) !!}
{!! csrf_field() !!}
<div class="form-group">
{!! Form::label('make', 'Manufacturer') !!}
{!! Form::select('make', ['Intel', 'AMD', 'Apple', 'Qualcomm', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('chipset', 'Chipset') !!}
{!! Form::text('chipset', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('type', 'Type') !!}
{!! Form::text('type', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('category', 'Category') !!}
{!! Form::select('categories', $categories, null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Add Processor', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
我只是想實現的東西相當於這個
<select class="form-control" name="category">
<?php
$stmt = $connect->prepare("SELECT * FROM categories");
$stmt->execute();
while($row = $stmt->fetch())
{
print "<option value='".$row['id']."'>".$row['name']."</option>";
}
?>
</select>
我的類別型號
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function processor()
{
return $this->hasMany('App\Processor', 'category_id');
}
}
我的處理器型號
use Illuminate\Database\Eloquent\Model;
class Processor extends Model
{
protected $fillable = ['make', 'chipset', 'type', 'category_id'];
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
}
我試過了,但它說:「在Builder.php中的BadMethodCallException行2450: 調用未定義的方法Illuminate \ Database \ Query \ Builder :: lists()」 –
我已更新我的答案檢查它。 –
你不需要在'compact()'函數內傳遞'$ categories'作爲第二個參數。 –