将参数传递给Laravel toArray()Eloquent Model

时间:2015-11-07 18:39:32

标签: php laravel-5.1

我的Controller中有一个方法:

function getSuggestions()
{
   $query = Input::get('query');
   $suggestions = Suggestion::where('word', 'LIKE', "$query%")->get()->toArray();
   $return $suggestions; 
}

并在Model我有:

 public function toArray(){
        $array = parent::toArray();
        $array['matched'] = 'ok';
        return $array;
    }

如何将变量传递给此toArray()方法以将其附加到Model? 这样的事情:$array['matched'] = $query 我无法将$query直接传递给toArray($query)。还有别的吗?

1 个答案:

答案 0 :(得分:1)

只需将值添加到每个匹配的数组:

function getSuggestions()
{
    $query = Input::get('query');
    $suggestions = Suggestion::where('word', 'LIKE', "$query%")->get()->toArray();
    return array_map(
        function ($array) use ($query) { $array['matched'] = $query; return $array; },
        $suggestions
    );
}