Answer the question
In order to leave comments, you need to log in
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);
}
$images = $user->images()->with(['tags' => function($query) use ($request) {
if($request->has('tags')) {
$query->whereIn('tags.id', $request->tags);
}
}])->orderBy('id', 'desc')->paginate(15);
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);
}
Answer the question
In order to leave comments, you need to log in
$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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question