I'm trying to create a search form for my Laravel app. Basically a user can enter some fields (searchable model related, like the title) and sort it in different ways; title, create date, but also vote count or favorite count. The last two are results from a pivot table (many to many relations).

I've been struggling with this but I don't know how to proceed. Here's what I have so far:

```
public function search(SearchRequest $request)
{
    $posts = Post::where('published', 1);

    if (strlen($request->title) > 0) {
        $posts->where('title', 'like', '%' . $request->title . '%');
    }

    switch($request->order_by) {
        case 'title' : $orderBy = 'title'; break;
        case 'createDate' : $orderBy = 'created_at'; break;
        case 'favorites' : $orderBy = 'post_favorites.count(*)'; break;
        case 'votes' : $orderBy = 'post_votes.count(*)'; break;
    }

    $posts->orderBy($orderBy, $request->order_by_direction);
    $posts = $posts->get();

    var_dump($posts);
}

```

To keep it simple I've rewritten the code to a typical blog post example. Thanks for your suggestions.