In your controller
public function create()
{
$towns = App\Town::orderBy('name', 'desc')->get();
return view('company.create')
->with('towns', $towns);
}
Ref: https://laravel.com/docs/5.5/views#passing-data-to-views
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello,
I am a bit confused on how to use the controllers/models in the right way.
I have 2 tables:
-Companies and towns
I have created a form that shows here "company/create.blade.php":
public function create()
{
return view('company.create');
}
In this form I would like to populate the dropdown menu with towns from the town table.
I currently have a company model, controller and a town model and controller.
The form is showing fine but as soon as I try to pass the dropdown values from the town table, I receive errors(see below).
use App\Town;
public function create()
{
$towns = App\Town::all();
return view('company.create', ['towns' => $towns]);
}
I have also tried this but same error.:
public function create()
{
$towns = App\Town::all()->orderBy('name', 'desc')->get();
return view('company.create', compact('towns'));
}
In the company/create.blade.php I added this:
<div class="form-group{{ $errors->has('towns') ? ' has-error' : '' }}">
<label for="towns" class="col-md-4 control-label">Select a Town</label>
<div class="col-md-6">
<select class="form-control" id="town">
<option value="">Select a Town</option>
@foreach ($towns as $town)
<option value="{{ $town->id }}">{{ $town->name }}</option>
@endforeach
</select>
@if ($errors->has('towns'))
<span class="help-block">
<strong>{{ $errors->first('towns') }}</strong>
</span>
@endif
</div>
</div>
I was expecting to have the form populated from the table "town" but instead, I am getting this:
ErrorException (E_ERROR) Undefined variable: towns (View: C:\laragon\www\kolloxmt\resources\views\company\create.blade.php)
Any idea what am I doing wrong please?
Please or to participate in this conversation.