Search code examples
phpeloquentlaravel-3

Laravel 3, Eloquent: SELECT with multiple WHERE conditions


I know this is going to be a simple one, and I've looked ... I must just be missing it.
It's been a while since I've coded in Laravel (or, at all for that matter :), and I can really use a nudge in the right direction.
FYI, this is for a REST-ish web service, so there's really no UI.

GOAL:
Process Find requests against the people table where the request can be for one field, or five fields, or anywhere in between.
Here are the $accessible fields:

  • fname
  • mi
  • lname
  • aka
  • gender

EXAMPLE REQUESTS:

  • $input = array('aka'=>'sammy','gender'=>'female')
  • $input = array('fname'=>'william','aka'=>'will')
  • $input = array('fname'=>'william','lname'=>'smith')
  • $input = array('lname'=>'smith')
  • etc., etc., etc...

TRIED:
A)

$payload = new PersonEntity( (array)$input ); 

B)

$model = new PersonEntity( (array)$input );  
$payload = $model->get();

C)

$model = new PersonEntity;

foreach( $input AS $field => $value )
{
    if( in_array($field, $model::$accessible))
    {
        $model->where( $field, '=', $value );
    }
}

$results = $model->get();

EXPECTING:
I am expecting the return of an array of objects which match the request.

RECIEVING:
Depending on what I'm trying at the moment, when I do get results, the entire table is returned.
Via the profiler, I'm able to see that it's simply running SELECT * FROM people.


Solution

  • I'm not sure I did understand but with Laravel you can chain where conditions in this way:

    $model = DB::table('people');
    
    $model = $model->where(function($model)
    {
        foreach( $input AS $field => $value )
        {
            if( in_array($field, $model::$accessible))
            {
                $model->where( $field, '=', $value );
            }
        }
    });
    
    $results = $model->get();