如何在Laravel 4中执行动态查询

时间:2013-10-04 05:26:43

标签: php mysql laravel laravel-4

我是laravel的新手。我正在尝试从选择列表构建查询。我收到以下错误

strtolower()期望参数1为字符串

这是我的表格

        <form action="search" method="post" accept-charset="utf-8">
                <div class="form-group">

                    <select  name="temptype" class="form-control">
                        <option value="" selected="selected">Select Temp Type</option>
                        <option value="hygienist" >Hygienist</option>
                        <option value="dentist" >Dentist</option>
                        <option value="dentalassistant" >Dental Assistant</option>
                    </select>

                </div><!-- end username form group -->
        </div><!-- end .modal-body -->
        <div class="modal-footer">
            <input type="submit" name="submit"  class="btn btn-primary" />
        </div>
        </form>

这是我的路线

Route::post('search', function(){


    $temp = User::getTemps();

    return $temp;


});

以下是我的用户模型中的方法...

 public static function getTemps()
    {

        $type = array (

            'hygienist' => Input::get('hygienist'),
            'dentist' => Input::get('dentist'),
            'dentalassistance' =>Input::get('dentalassistance')

        );


        $temps = DB::table('users')
            ->select('usertype', $type) <---- I think this has to be a string but my question is how do I make this dynamic... How do I pass the string value from what the user selects and pass it into the query?>
            ->get();

        return $temps;
    }

1 个答案:

答案 0 :(得分:1)

您的表单永远不会发布卫生师牙医 dentalassistance 。因此Input::get('hygienist')将是null。表单将使用选择列表中选定的发布 temptype 。也就是说,如果我转到该表单,请选择 Hygienist 并点击提交,您将拥有Input::get('temptype') = "Hygienist"

因此,您应将getTemps更改为:

public static function getTemps()
{
    // Create a array of allowed types.
    $types = array('hygienist', 'dentist', 'dentalassistance');

    // Get what type the user selected.
    $type = Input::get('temptype');

    // Make sure it is a valid type.
    if(!in_array($type, $types))
    {
        return App::abort(500, "Invaild temptype.");
    }



    $temps = DB::table('users')
        ->select('usertype', $type)
        ->get();

    return $temps;
}