简体   繁体   中英

Pass Parameter to Laravel toArray() Eloquent Model

I've a method in my Controller :

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

and in Model I have:

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

How can I pass a variable to this toArray() method to append it to the Model ? Something like this: $array['matched'] = $query I can't pass the $query directly to toArray($query) . Any other way?

Just add the value to each matched array:

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
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM