Skip to content
Advertisement

Laravel 7 relationship query data not working

I would like to query companies name through employees. Why didnt get any result? It not give any error.

Companies model

    public function employees() {
        return $this->hasMany(Employees::class);
    }

Employees model

   
    public function companies() {
        return $this->belongsTo(Companies::class);
    }

Employees controller

     public function createIndex() {

        $employees = Employees::all();

        return view('employees.create', [
            'employees' => $employees
        ]);
    }

Where i like to query

            <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

        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 …

 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:

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

 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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement