Model::map() (jQuery.map style)

Submitted by jplozano - 4 years ago

This scope function applies a callback to the elements of a given query collection.

    /**
     * Applies the callback to the elements of the given query collection
     *
     * @param $query
     * @param \Closure $callback
     * @param string|boolean $glue
     * @return string|array
     */
    public function scopeMap($query, $callback, $glue = '')
	{
		$collection = array();
		$i = 0;

		foreach($query->get() as $row){
			$collection[] = $callback($row, $i);
			$i++;
		}

		return $glue !== false ? implode($glue, $collection) : $collection;
	}
    
    /*
    // Example:
     
    // It returns an array of elements
    $fruits = Fruit::map(function($item, $i){
        return $item->name;
    });
    
    echo HTML::ul($fruits); 
    
    // Echoes:
    // <ul>
    //  <li>Lemon</li>
    //  <li>Orange</li>
    //  <li>Apple</li>
    // </ul>
    
    // If you want to glue it, just pass a second argument:
    $fruits = Fruit::map(function($item, $i){
        return $i.'. '.$item->name;
    }, ', ');
    
    // Echoes:
    // 0. Lemon, 1. Orange, 2. Apple
    *