在Laravel中构建动态查询 - 如何进行多选项搜索

So I am trying to set up a search page and it has multiple get options But I am curious as to how to set this up correctly, I know this is far from correct as I am doing if statements inside of setting a variable, But I am so lost right now.

Any help would be greatly appreciated.

public function index()
{

    $queryUsername = Request::get('u');
    $queryPostcode = Request::get('p');
    $queryOrderbyPhotos = Request::get('o1');
    $queryOrderbyOnline = Request::get('o2');
    $queryOrderbyTypes = Request::get('o3');

    $users = User::rightJoin('user_profiles','users.id', '=', 'user_profiles.user_id')

    if ($queryUsername) 
    {
        ->where('users.username', '=', "$queryUsername")
    }
    if ($queryPostcode) {   
        ->where('user_profiles.postcode', '=', "$queryPostcode")
    }
    if ($queryOrderbyPhotos) {  
        ->whereNotNull('user_profile.avatar')
    }
    if ($queryOrderbyOnline) {  
        ->orderBy('users.last_online', 'DESC')
    }
    if ($queryOrderbyType) {    
        ->orderBy('users.type', 'DESC')
    }
    ->get();

    return view('view', compact('users'));
}

This is how I'll approach the problem. I'll create a variable holding the query builder and then call all the additional query methods on it.

With Eloquent and actually with any class that allows Method Chaining you can do this:

$query = User::select(...)->join(..);
$query->where(...);
$query->get(...);

So in your case I'll be trying to achieve what you want in this manner:

   public function index()
    {
        $input = Request::all();

        $query = User::rightJoin('user_profiles', 'users.id', '=', 'user_profiles.user_id');

        if (isset($input['u']) && $input['u'])
            $query->where('users.username', '=', $input['u']);

        if (isset($input['p'])  && $input['p'])
            $query->where('user_profiles.postcode', '=', $input ['p']);

        if (isset($input['o1']) && $input['o1'])
            $query->whereNotNull('user_profile.avatar');

        if (isset($input['o2']) && $input['o2'])
            $query->orderBy('users.last_online', 'DESC');

        if (isset($input ['o3']) && $input['o3'])
            $query->orderBy('users.type', 'DESC');

        $users = $query->get();

        return view('view', compact('users'));
    }

Of course it will be a good idea that you have an additional check for valid input on each input parameter. But this can be achieved in many ways. You can read more about Laravel Controller Validation or Laravel Form Request Validation

By the way I'll suggest to move all this code in your model or in separate class as I prefer keeping controllers slim.

You can try :

$users_query = new User;
$users_query->rightJoin(....);

if ($queryUsername)
{
    $users_query->where('users.username', '=', "$queryUsername")
}
// Your other conditions .....
....

$users = $users_query->get();