laravel - (laravel4) printing out posts with tags -
i'm trying print tags along posts (which named tutorials).
class homecontroller extends basecontroller { public function index() { $tutorials = tutorial::where('draft', '=', 0)->get(); $tags = $tutorials->first()->tags()->get(); homecoming view::make('home', array( 'tags' => $tags, 'tutorials' => $tutorials )); } }
if works, first tag there is, , not tag belongs tutorial. i've been trying work since yesterday i'm stuck 1 time again...
tutorial model:
class tutorial extends eloquent { protected $table = 'tutorials'; public function tags() { homecoming $this->belongstomany('tag', 'tutorials_tags', 'tutorial_id'); } }
tag model:
class tag extends eloquent { protected $table = 'tags'; public function tutorials() { homecoming $this->belongstomany('tutorial', 'tutorials_tags', 'tag_id'); } }
home view:
@foreach($tutorials $tutorial) <p>{{$tutorial->title}}</p> <p>{{$tutorial->body}}</p> @foreach($tags $tag) <p><b>tags:</b> {{$tag->name}}</p> @endforeach <br> @endforeach
you controller code bit ambiguous, assume want list tutorials, along tags associated each tutorial.
you can utilize laravel's eager loading that, hint: with('tags')
. tell laravel that, hey when fetch tutorials me, bring them "with tags". don't need fetch tags separately you're trying do.
so in homecontroller:
class homecontroller extends basecontroller { public function index() { $tutorials = tutorial::with('tags')->where('draft', '=', 0)->get(); homecoming view::make('home', array( 'tutorials' => $tutorials )); } }
and view:
@foreach($tutorials $tutorial) <p>{{$tutorial->title}}</p> <p>{{$tutorial->body}}</p> @foreach($tutorial->tags $tag) <p><b>tags:</b> {{$tag->name}}</p> @endforeach <br> @endforeach
laravel eloquent relationship
No comments:
Post a Comment