create a scope on Post model like;
public function scopeAuthor($query,$author)
{
if(!Empty($author)){
return $query->whereHas('author', function ($query) use ($author) {
$query ->where('username', 'like', "%{$author}%");
}
return $query;
}
Then you can use this to filter your posts
change the controller like;
$search = $request->search;
$filter = $request->filter;
$append = array();
if($search){
switch ($filter) {
case 'username':
$posts = Post::author($search)->with('author')->with('categories')->latest();
break;
}
$append += array('search' => $search);
$append += array('filter' => $filter);
}
$posts = $posts->paginate(3);
$posts->appends($append);
return view('core.blog.posts.index', compact('posts'));
So, it passes the search term to the scope
the scope checks if a search term has been passed (so it works if no search specified) and then uses WhereHas to limit posts to only those having an author named like the search term