mercredi 25 janvier 2017

Getting all item from choosen tag with Laravel

I have one page where I show image + tags added to image. I want to make tags clickable and when I click on some tag to open all images which has this tag too.

I have 3 tables: images for images, tags for tags and image_tag for tags assigned to images with columns (image_id and tag_id). My models are

In Tag model I've added this relation

public function byTags() {    
    return $this->belongsToMany('App\Image', 'item_tag');  
}

I've added also this to my Image model but I'm not sure if I need it

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

This is the href link which should load all images

<a href="{!! url('byTag/' . $tag->id) !!}"> {!! $tag->tag !!} </a>

This is my route

Route::get('byTag/{tag_id}', 'ImageController@byTag')->name('bytag');

byTag() function in the ImageController

public function byTag($tag_id){

    $images = Tag::with('byTags')->whereId($tag_id)->get();
    return view('bytag', compact('images'));          
}

What is happen when I click on the button is that I get the tag on the view bytag instead of the images with this tag.

What I miss here?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire