Home > Mobile >  Call to undefined relationship [competency] on model [App\Models\Summary]. Laravel 9
Call to undefined relationship [competency] on model [App\Models\Summary]. Laravel 9

Time:08-03

I have two tables, Summary and Competency, I just met this error when I was trying to show foreign key data from Competency into table Summary.

Here is my Summary model:

class Summary extends Model
{
    protected $table = "summary";
    protected $primaryKey = "id";
    protected $fillable = [
        'id', 'competency_id', 'price'
    ];

    public function competency_id()
    {
        return $this->belongsTo(Competency::class);
    }
}

Here is my Competency model:

class Competency extends Model
{
    protected $table = "competency";
    protected $primaryKey = "id";
    protected $fillable = [
        'id', 'competency_name'
    ];

    public function summary()
    {
        return $this->hasMany(Summary::class);
    }
}

My SummaryController

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Summary;

class SummaryController extends Controller
{
    public function index()
    {
        $summaryData = Summary::with('competency')->get();
        return view('dashboard', compact('summaryData'));
    }
}

My dashboard.blade.php

<tbody>
  @foreach ($summaryData as $item)
      <tr>
          <td>{{$loop->iteration}}</td>
          <td>{{$item->competency->competency}}</td>
          <td>{{$item->price}}</td>
          <td>
          <a href="{{url('edits', $item->id)}}" >Edit</a>
          <a href="{{route('delete', $item->id)}}"  >Delete</a>
          </td>
      </tr>
  @endforeach
</tbody>

I really appreciate your answers.

CodePudding user response:

In your model you declared the method name as:

public function competency_id

And when you called it with eager loading you did:

$summaryData = Summary::with('competency')->get();

You are trying to call competency relationship while it's name is competency_id. Just change the method name in your model to competency and you should be good to go

CodePudding user response:

You are calling wrong method name of relationship.

Your relationship method name is competency_id and you are calling it competency, which will throw error.

Either you change method name to competency or call is as below:

$summaryData = Summary::with('competency_id')->get();

Hope this will be helpful.

CodePudding user response:

in summary class you shave to

replace

public function competency_id()
    {
        return $this->belongsTo(Competency::class);
    }

to

public function competency()
    {
        return $this->belongsTo(Competency::class);
    }
  • Related