Usman Developer
Usman Developer

Reputation: 578

unable to define relationship in laravel 5.7

I have two table as sbj_topics and difficulty_level_sbj_topic so, I want to define relationship b\w them to fetch records, so to make relationship I have done this,

SbjTopic.php:

public function difficulty_level_sbj_topic() {
    return $this->hasMany('App\DiffiLvlSbjTopic');
}

And in DiffiLvlSbjTopic.php:

protected $table = 'difficulty_level_sbj_topic';
public function sbj_topics() {
    return $this->belongsTo('App\SbjTopic');
}

After that I returned the data to a view as:

$easy = DiffiLvlSbjTopic::where(['subject_id' => $id, 'difficulty_level_id' => 2])->get();
return view('diffi_lvls.show', compact('easy'));

Then in the view I done this:

@foreach($easy as $easy)
    {{ $easy->sbj_topics }}
@endforeach

but the page is blank, and when I do this {{ $easy->sbj_topics->sbj_topic_name }} trying to get property of undefined! comes.

The main purpose of creating relationship is to display Subject Topic Name because I have foreign key as sbj_topic_id in difficulty_level_sbj_topic table so if anyone has any other idea to do this without relationship that will be awesome.

Upvotes: 2

Views: 61

Answers (2)

Johhn
Johhn

Reputation: 1049

Break this down:

  • SbjTopic - has many difflevels
  • a difflevel belongs to aSbjTopic

With this understanding, I can see you are getting the difflevels (DiffiLvlSbjTopic). This is actually what you are passing to your blade.

So first off: complete your relationship by specify the foreign keys. i.e: In the SbjTopics model:

public function difficulty_level_sbj_topic() {
    return $this->hasMany('App\DiffiLvlSbjTopic', 'subject_id');
}

with this, you know that in the 'difficulty_level_sbj_topic' you must have the column subject_id. Now define the reverse relationship in your DiffiLvlSbjTopic model:

public function sbj_topics() {
    return $this->belongsTo('App\SbjTopic', 'subject_id');
}

With all these in place in your controller or route all you need to do is fetch the DiffiLvlSbjTopic model properties. For instance:

public function index () {
     $easy = DiffiLvlSbjTopic::all();
     return view('diffi_lvls.show', compact('easy'));
}

Finally in your view:

@foreach($easy as $difflevel)
    <div>{{ $difflevel->sbj_topics->name }} </div>
@endforeach

That's it.

Upvotes: 3

Iftikhar uddin
Iftikhar uddin

Reputation: 3192

Your both variables should not be $easy it can be something like $easy as $easySingle. And add a loop inside like

@foreach($easy as $easySingle)
    foreach ($easySingle->sbj_topics as $topic) {
      $topic->property;
    }   
@endforeach   

Upvotes: 2

Related Questions