Laravel Eloquent is looking for two optional fields

I am trying to search for two optional tables using eloquence:

$users  = User::where('ProfileType', '=', 2)
                ->where(function($query) {
                    $query->where('BandName', 'LIKE', "%$artist%");
                    $query->or_where('Genre', 'LIKE', "%$genre%");
                })->get();

This is great for returning all results when the user performs an empty search, but I'm not sure how to configure this to search for a range name when it is present, and vice versa.

+1
source share
3 answers

Based on Vinicius answer, here's what worked:

// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');

// Adds a clause to the query
if ($artist = Input::get('artist')) {
    $query->where('BandName', 'LIKE', "%$artist%");
    // Temp Usernamesearch
    $query->or_where('NickName', 'LIKE', "%$artist%");
}

// Genre - switch function if artist is not empty
if ($genre = Input::get('genre')) {
    $func = ($artist) ? 'or_where' : 'where';
    $query->$func('Genre', 'LIKE', "%$genre%");
}

// Executes the query and fetches it results
$users = $query->get();

It turns out that the second optional field should use or_where only if $ artist is not set.

thanks for the help

+2
source

Just to explain what happens in response below:

: User::where(...), Database\Query. , DB::table('users')->where(...), SQL-.

, :

// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
$query->where(function($query) {
    // Adds a clause to the query
    if ($artist = Input::get('artist')) {
        $query->where_nested('BandName', 'LIKE', "%$artist%", 'OR');
    }
    // And another
    if ($genre = Input::get('genre')) {
        $query->where_nested('Genre', 'LIKE', "%$genre%", 'OR');
    }
});

// Executes the query and fetches it results
$users = $query->get();
+8

I think this is what you are after. Your submission will have the form to search for an artist / genre that can be set, or both, or not.

$users = User::where('ProfileType', '=', 2);

if (Input::has('artist')) {
    $users = $users->where('BandName', 'LIKE', '%'.Input::get('artist').'%');
}

if (Input::has('genre')) {
    $users = $users->where('Genre', 'LIKE', '%'.Input::get('genre').'%');
}

$users = $users->get();
0
source

All Articles