S
S
Sergey Khlopov2021-04-03 11:44:56
Laravel
Sergey Khlopov, 2021-04-03 11:44:56

How to get user images by tag?

Hello, tell me please. I have an image model and it has a method

public function tags(): BelongsToMany
{
   return $this->belongsToMany(Tag::class);
}

An image can have many tags, a tag can have many images.
And now I don’t understand a little how I can make a request, I need to display images for the selected tag.
I did this first, but it doesn't work as expected.
In $request->tags - array of id of selected tags
$images = $user->images()->with(['tags' => function($query) use ($request) {
  if($request->has('tags')) {
    $query->whereIn('tags.id', $request->tags);
  }
}])->orderBy('id', 'desc')->paginate(15);


And this is how it works:
if($request->has('tags')) {
  $images = $user->images()->whereHas('tags', function (Builder $query) use ($request) {
    $query->whereIn('tags.id', $request->tags);
  })->orderBy('id', 'desc')->paginate(15);
}
else {
  $images = $user->images()->orderBy('id', 'desc')->paginate(15);
}


But I'm thinking maybe it's possible to do something differently, tell me please, thank you in advance for the answer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kudrya, 2021-04-03
@Mugenzo

$images = $user->images()
  ->when($request->has('tags'), function($q) use ($request) { 
      $q->whereHas('tags', function ($q) use ($request) {
         $q->whereIn('tags.id', $request->tags);
      })
  })
  ->orderBy('id', 'desc')->paginate(15);

Try this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question