I would like to query companies name through employees. Why didnt get any result? It not give any error.
Companies model
JavaScript
x
public function employees() {
return $this->hasMany(Employees::class);
}
Employees model
JavaScript
public function companies() {
return $this->belongsTo(Companies::class);
}
Employees controller
JavaScript
public function createIndex() {
$employees = Employees::all();
return view('employees.create', [
'employees' => $employees
]);
}
Where i like to query
JavaScript
<div class="form-group">
<label for="company">Company: </label>
<select name="company" class="form-control">
@foreach($employees as $employe)
<option selected>Choose</option>
@foreach($employe->companies as $company)
<option id="company">{{ $company->name }}</option>
@endforeach
@endforeach
</select>
</div>
This is the migrations for tables
JavaScript
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email');
$table->string('logo');
$table->string('website');
$table->timestamps();
});
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('fname');
$table->string('lname');
$table->string('email');
$table->string('phone');
$table->bigInteger('companies_id')->unsigned();
$table->timestamps();
$table->foreign('companies_id')->references('id')->on('companies')
->onDelete('cascade');
});
Advertisement
Answer
please provide the foreign key to your relation …
JavaScript
public function companies()
{ return $this->belongsTo(Companies::class,'companies_id'); }
this relation means that the employee has only one company (belongs To one company)
so you can’t iterate over it!
in this line:
JavaScript
@foreach($employe->companies as $company)
<option id="company">{{ $company->name }}</option>
@endforeach
employe->companies will return only one object .. if you want to show all companies as options, pass $allCompany like:
JavaScript
public function createIndex() {
$employees = Employees::all();
$compnanies = Companies::all();
return view('employees.create', [
'employees' => $employees,'compnanies'=> $compnanies
]);
}
then you can iterate $compnanies in your view