Search code examples
laravelmany-to-manypivot-table

Laravel accessing pivot table name field in a Many to Many relation


I am retrieving the latest 4 rows from my Sermon table and passing it to a view with View Composer. but i don't know how i can access the tags attached to each sermons

namespace App\Http\ViewComposers;
use App\Sermon;
use App\Tags;

use Illuminate\View\View;

class SermonComposer
{
public function compose(View $view)
{

    $sermons = Sermon::take(4)->orderBy('id','DESC')->get();


    $view->with('sermons', $sermons );


}

}

How can I access the name of the tags related to a single sermon? a sermon could have multiple Tags

this is what i have in my Sermon model

public function tag()
{
    return $this->belongsToMany('App\Tag');
}

this is my blade

 @foreach ($sermons as $sermon )
            <tr>
                <td>{{$sermon->id}}</td>
                <td>{{$sermon->title}}</td>

                <td>{{$sermon->pivot->name}}</td>
                <td><img src="{{ asset('img/sermons/'. $sermon->sermon_image)}}" alt=""></td>
                <td><a href="#">@include('svg.edit')</a></td>
            </tr>
        @endforeach

if i {{dd($sermons)}} this is what i get and i noticed my relations array is empty

enter image description here


Solution

  • It's many to many relationship so you should use a plural name as relation like

    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
    

    After defining relation you have to eagar load your tags while querying using with().

    public function compose(View $view)
    {
    
        $sermons = Sermon::with('tags')->take(4)->orderBy('id','DESC')->get();
    
        $view->with('sermons', $sermons );
    
    }
    

    And after that in blade view, you can do like this

    @foreach ($sermons as $sermon )
            <tr>
                <td>{{$sermon->id}}</td>
                <td>{{$sermon->title}}</td>
                @foreach ($sermon->tags as $tag )
                <td>{{$tag->name}}</td>
                @endforeach
                <td><img src="{{ asset('img/sermons/'. $sermon->sermon_image)}}" alt=""></td>
                <td><a href="#">@include('svg.edit')</a></td>
            </tr>
    @endforeach
    

    This is just example I am giving your problem may be different. Show the blade view if you want the more specific answer.

    If you have any doubts, please comment.