I need to show posts by tags. My solution works for single tag and it looks as follows:
Route:
Route::get('/posts',
[PostController::class, 'index'])->middleware('auth');
Post model filter:
public function scopeFilter($query, array $filters)
{
if ($filters['tag'] ?? false) {
$tagId = Tag::where('name', $filters['tag'])->first()->id;
$query->whereHas('tags', function($q) use ($tagId) {
$q->where('tag_id', $tagId);
});
}
}
Method index from PostController:
public function index()
{
return view('posts', [
'posts' => Post::latest()->filter(request(['tag']))->get()
]);
}
This code works for url as follows: "http://127.0.0.1:8000/posts/?tag=test". But I need to find a way to be able search posts that have more tags, for example I would like find posts with "test" and "unit" tags. For this I would like to use url as follows: "http://127.0.0.1:8000/posts/?tag=test&unit". I stuck, because I was thinking that "request([‘tag’])" will return "test&unit" but it only return "test". Is it even possible to get in some way also ‘unit’ tag from this request?
2
Answers
What you can do is seperate it by comma so your url will by ?tag=test,unit
the code will look like this (untested)
I will explain the code later today
A
GET
request using a Query String can accept multiple parameters. Instead of?tag=test&unit
(which wouldn’t really work anyway, since&unit
would be parsed as$request->input('unit')
, and would benull
,&
is a reserved character), you’d send it as:On the backend, when you access
request()->input('tags')
, you’d get the following array:So, putting it all together:
whereIn()
to handle multiple valuesrequest()->input('tags', [])
to access?tags[]=...&tags[]=...
, or an empty Array if not supplied.