How to show name from id using relationship in laravel 5.6?

Viewed 143

I want to show rta name in the table, but it gives me error

Issuer Model Function

public function rtalist(){
    return $this->belongsTo('App\RTAList','rta_id','id');
}

RTAList Model

protected $table = 'rta_list';
protected $fillable = ['rta_name','dp_type','rta_address','rta_phone','rta_email','dp_status','setup_date'];

Code in Issuer Controller

 $data = Issuer::with('rtalist')->get();
    return view('admin.issuer.view_all_issuer')->with(compact('data'));

In view_issuer.blade.php

  <td style="text-transform: uppercase;">{{ $issuers->rta_list->rta_name }}</td>

But it gives me this error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rta_list.id' in 'where clause' (SQL: select * from rta_list where rta_list.id in (3, 4))

How to solve this problem and show name instead of id..

3 Answers

Your relation should be like this

public function rtalist(){
    return $this->belongsTo('App\RTAList','rta_list_table_primary_key','Issuer Model table foreign key');
}

And it should work.

Remove the param "id" and in the secund param add 'your_compost_table_name':

public function rtalist(){
  return $this->belongsTo('App\RTAList', 'your_compost_table_name', 'rta_id');
}

or try:

public function rtalist(){
  return $this->belongsTo('App\RTAList', 'rta_id');
}

The issue is you didn't have Primary Key in rta_list table with name id. You must have structure as below

Issuer Table

id --primary_id
rta_list_id --foreign_key
.
.
....

RTAList Table

p_id --primary_id
rta_name
.
.
....

Now make relation like below

public function rtalist(){
    return $this->belongsTo('App\RTAList', 'rta_list_id', 'p_id');
}
Related