1

On my website, users can upload images and attach tags to those images.

I've got an images table,a tag table and an images_tag pivot table.

Images can have many tags, and tags can belong to many images.

I want to be able to generate a list of all the tags a user has used in his/her images.

$imageIDs = Images::where('created_by', Auth::user()->id)->lists('id');

So this would create a list of all the image IDs that a user has upload.

What I want is essentially "foreach $imageIDs, check the images_tag table and for every match go to the tags table and get me back the tagname value."

But I have no idea how I'd do that.

Maybe a foreach then use the merge method on all the results? Any help would be appreciated!

2 Answers 2

1

You need to use whereHas() to check the relationship:

$userTags = Tags::whereHas('images', function($q) {
    $q->where('created_by', auth()->user()->id);
})->get();

Then just pass this data to a view:

return view('some.view', compact('userTags'));

And iterate over tags in a view:

@foreach ($userTags as $tag)
    {{ $tag->name }}
@endforeach
Sign up to request clarification or add additional context in comments.

Comments

1

What you could do is this.

class Tag extends Model
{
    public function images()
    {
        return $this->belongsToMany(Image::class);
    }
}

class SomeController
{
    public function someMethod()
    {
        $tags = Tag::with(['images' => function ($image) {
            return $image->where('created_by', Auth::user()->id);
        }])->select('id', 'tagname')->get();
        // these are your $tags 
    }
}

You should not use a query inside foreach(). Then it would result N+1 problem. What you instead do is eager loading using with() statement.

4 Comments

You're getting a collection. $tag collection contains all the tags matches your query. laravel.com/docs/5.3/collections
Fair enough. So I already had the first functions, images(), in my Tag model doing the whole belongsToMany thing. However, I'm not sure how someMethod would work. I'm still fairly new to Laravel. How would I call this function in my controller so that I could return the view with $tags?
Please consider SomeController and someMethod() a dummy Class and a Method since I don't know your code structure. You only gonna need the query part.
@FelixMaxime since you mentioned you are fairly new I suggest you watching laracasts.com/series/laravel-5-fundamentals

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.