Skip to content

Instantly share code, notes, and snippets.

@JonasDoebertin
Last active July 12, 2016 08:40
Show Gist options
  • Save JonasDoebertin/2ded1b627e2f870b53a387ac21634f01 to your computer and use it in GitHub Desktop.
Save JonasDoebertin/2ded1b627e2f870b53a387ac21634f01 to your computer and use it in GitHub Desktop.
Laravel Collection Macros
<?php
/**
* Copyright © 2015-2016 »jd« powered. All rights reserved.
*
* @copyright Copyright © 2015-2016 »jd« powered
* @link http://jd-powered.net
* @author Jonas Döbertin <hello@jd-powered.net>
*/
namespace App\Providers;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
class CollectionServiceProvider extends ServiceProvider
{
/**
* Register
*/
public function register()
{
//
}
/**
* Boot the collection extensions for the application.
*/
public function boot()
{
/**
* Get the mode value of a given key.
*
* @param string|null $key
* @return mixed
*/
Collection::macro('mode', function ($key = null) {
if (is_null($key)) {
$values = array_count_values($this->values()->toArray());
} else {
$values = array_count_values($this->pluck($key)->values()->toArray());
}
return array_search(max($values), $values);
});
/**
* Perform a regular expression search and replace.
*
* @param string $pattern
* @param string $replacement
* @param string|null $key
* @return mixed
*/
Collection::macro('replace', function ($pattern, $replacement, $key = null) {
return $this->transform(function ($item) use ($pattern, $replacement, $key) {
if (!is_null($key)) {
$item->{$key} = preg_replace($pattern, $replacement, $item->{$key});
} else {
$item = preg_replace($pattern, $replacement, $item);
}
return $item;
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment