Skip to content
Advertisement

calling relation with a parameter in the view

i know this has been asked alot , but none of the solution works for me as i want to use this in the view

i have 3 tables

Languages : id , title 
Blog : id 
BlogLanguage : blog_id , language_id , title , text 

so when i list the blogs in the view , for each blog i want to show what languages has been stores for this Blog

basically i want to do something like this

$blogs = Blog::all();
$languages = Language::all();
return view('blog-index' , compact('blogs' ,'languages));

in the view

@foreach($blogs as $blog )

  id : {{$blog->id}} 
  @foreach($languages as $lang )
   {{$lang->title}} : {{ $lang->HasThisBlog($blog->id) ? 'yes' : 'no' }}
  @endforeach

@endforeach 

here is what im stuck

{{ $lang->HasThisBlog($blog->id) ? 'yes' : 'no' }}

if i can have this relation in the Language model

function HasThisBlog($id){
 return $this->hasOne(BlogLanguage::class )->where('blog_id' , $id ) ;
}

of course this doesn’t work and gives me some weird object like

HasOne {#706 ▼
  #foreignKey: "blog_languages.language_id"
  #localKey: "id"
  #query: Builder {#705 ▶}
  #parent: Language {#560 ▶}
  #related: BlogLanguage {#667 ▶}
  #withDefault: null
}

Advertisement

Answer

You just need to define a relation on you Blog model. As you already have pivot table for the following relationships

Blog belongsToMany Language(s)

Language belongsToMany Blog(s)


class Blog extends Model
{
    public function languages()
    {
        return $this->belongsToMany(Language::class);
    }

    //....other code of the class
}

class Language extends Model
{
    public function blogs()
    {
        return $this->belongsToMany(Blog::class);
    }

    //... other code of the class
}

Then in blade view

@foreach($blogs as $blog)

    <p>{{ $blog->id }}</p>

    @foreach($languages as $language)
        <p>{{ $language->title }}: {{ $blog->languages->contains('id', $language->id) ? 'Yes' : 'No' }}</p>
    @endforeach

@endforeach

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