Adi Kurniawan Adi Kurniawan - 21 days ago 18
PHP Question

Proper way to populate dropdown from foreign key in Laravel 5.3

can anyone help me in solving this problem? I've been stuck for days with the error htmlspecialchars() expects parameter 1 to be string, array given in Laravel 5.3.

Here is my controller

public function create()
{
$categories = DB::table('categories')->pluck('name', 'id');
foreach($categories as $category)
{
echo $category;
}
return view('admin.processor.create', compact('categories', $categories));
}


And here's my view (the form)

{!! 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() !!}


I just want to achieve something equivalent to this

<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>


My Category Model

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
protected $fillable = ['name'];

public function processor()
{
return $this->hasMany('App\Processor', 'category_id');
}
}


My Processor Model

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');
}
}

Answer

Try this:

Controller

$categories = DB::table('categories')->pluck('name', 'id');
return view('admin.processor.create', compact('categories'));

View

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