Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Johnathon Koster
This book is for sale at http://leanpub.com/laravelcompanion
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools
and many iterations to get reader feedback, pivot until you have the right book and build
traction once you do.
I Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1. String Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1 Immutable Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 ascii($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 studly($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 camel($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 snake($value, $delimiter = '_') . . . . . . . . . . . . . . . . . . . . . 5
1.6 title($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7 slug($title, $separator = '-') . . . . . . . . . . . . . . . . . . . . . . 6
1.8 contains($haystack, $needles) . . . . . . . . . . . . . . . . . . . . . . 7
1.9 endsWith($haystack, $needles) . . . . . . . . . . . . . . . . . . . . . . 8
1.10 startsWith($haystack, $needles) . . . . . . . . . . . . . . . . . . . . . 9
1.11 finish($value, $cap) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.12 is($pattern, $value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.13 length($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.14 limit($value, $limit = 100, $end = '...') . . . . . . . . . . . . . . 11
1.15 words($value, $words = 100, $end = '...') . . . . . . . . . . . . . . 12
1.16 lower($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.17 upper($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.18 plural($value, $count = 2) . . . . . . . . . . . . . . . . . . . . . . . . 13
1.19 singular($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.20 singular Special Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.21 random($length = 16) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.22 quickRandom($length = 16) . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.23 randomBytes($length = 16) . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.24 equals($knownString, $userInput) . . . . . . . . . . . . . . . . . . . . 19
1.25 parseCallback($callback, $default) . . . . . . . . . . . . . . . . . . . 20
1.26 replaceFirst($search, $replace, $subject) . . . . . . . . . . . . . . 23
1.27 replaceLast($search, $replace, $subject) . . . . . . . . . . . . . . . 23
1.28 substr($string, $start, $length = null) . . . . . . . . . . . . . . . 24
1.29 ucfirst($string) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
CONTENTS
II Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
This icon will be used when defining a term. This icon is not used often, and usually
only applied when there may be confusion about or term, or when sufficient ambiguity
already exists around a term.
This icon is used to present the thoughts or opinions of the author(s) and acts as an
invitation for conversation. These sections also feature a title styling that is more subtle.
Look for this icon in the text to learn about any appendices that may additional
reference material for a given section.
This icon indicates information that is important or the cause of general errors.
This icon is used to point out or explain the cause of specific errors or problems that
may arise during development.
This icon is used to point out additional information that might be useful in the context
of a given chapter, but is not required.
¹https://leanpub.com/
²http://brackets.io/
³https://github.com/JohnathonKoster/brackets-spellcheck
CONTENTS iii
Here be dragons!
.~))>>
.~)>>
.~))))>>>
.~))>> ___
.~))>>)))>> .-~))>>
.~)))))>> .-~))>>)>
.~)))>>))))>> .-~)>>)>
) .~))>>))))>> .-~)))))>>)>
( )@@*) //)>)))))) .-~))))>>)>
).@(@@ //))>>))) .-~))>>)))))>>)>
(( @.@). //))))) .-~)>>)))))>>)>
)) )@@*.@@ ) //)>))) //))))))>>))))>>)>
(( ((@@@.@@ |/))))) //)))))>>)))>>)>
)) @@*. )@@ ) (\_(\-\b |))>)) //)))>>)))))))>>)>
(( @@@(.@(@ . _/`-` ~|b |>))) //)>>)))))))>>)>
)* @@@ )@* (@) (@) /\b|))) //))))))>>))))>>
(( @. )@( @ . _/ / / \b)) //))>>)))))>>>_._
)@@ (@@*)@@. (6///6)- / ^ \b)//))))))>>)))>> ~~-.
( @jgs@@. @@@.*@_ VvvvvV// ^ \b/)>>))))>> _. `bb
((@@ @@@*.(@@ . - | o |' \ ( ^ \b)))>> .' b`,
((@@).*@@ )@ ) \^^^/ (( ^ ~)_ \ / b `,
(@@. (@@ ). `-' ((( ^ `\ \ \ \ \| b `.
(*.@* / (((( \| | | \ . b `.
/ / ((((( \ \ / _.-~\ Y, b ;
/ / / (((((( \ \.-~ _.`" _.-~`, b ;
/ / `(((((() ) (((((~ `, b ;
_/ _/ `"""/ /' ; b ;
_.-~_.-~ / /' _.'~bb _.'
((((~~ / /' _.'~bb.--~
(((( __.-~bb.-~
.' b .~~
:bb ,'
~~~~
I Helper Functions
“Science makes people reach selflessly for truth and objectivity; it teaches people to accept
reality, with wonder and admiration, not to mention the deep awe and joy that the natural order
of things brings to the true scientist.”
– Lise Meitner (1878 - 1968), Physicist
Laravel has a number of helper functions that will make developing applications even easier.
Most of them are utility based, such as determining if an array has an item, or if a string
starts with a particular string or character. All functions will be organized by category and then
grouped by their behavior. Functions that do not have a logical grouping will then appear in the
order they appear in when viewing the helper files.
1. String Helper Functions
String operations in PHP often seem complicated to developers coming to the language from
other language, specifically languages that have a robust object-oriented approach to the
provided data types. Operations such as checking if a particular string contains a substring, or
if a string starts or ends with another string are not impossible, nor are they difficult, they just
appear over-complicated or obscure. Luckily for us, Laravel has an amazing collection of string
helper functions that we can use to perform some of the most common actions. The string helper
functions are kept in the static class Illuminate\Support\Str. The following functions are
not necessarily in the same order that they will appear in the class. They have been grouped
based on their functionality and purpose.
1 use Illuminate\Support\Str;
2
3 $firstString = 'my words';
4
5 // Returns `MyWords`
6 Str::studly($firstString);
7
8 // Displays 'my words'
9 echo $firstString;
1.2 ascii($value)
The ascii helper method accepts only one argument: $value. $value should always be a string,
or something that can be cast into a string. The function converts a string in the UTF-8¹ encoding
into it’s ASCII² equivalent.
This function is useful when communicating with other software platforms that require ASCII,
or when complying with protocols (such as HTTP) about how headers, or some values, need to
be formatted.
Example use:
¹http://en.wikipedia.org/wiki/UTF-8
²http://en.wikipedia.org/wiki/ASCII
2
String Helper Functions 3
1 use Illuminate\Support\Str;
2
3 // The following will output "a test string"
4 // in the ASCII encoding.
5
6 echo Str::ascii('a test string');
As of Laravel 5, the ascii function internally uses the stringy³ library. Previous
versions of Laravel have used the patchwork/utf8⁴ package.
1.3 studly($value)
Studly caps is a way of formatting text with capital letters, according to some pattern. Laravel’s
pattern is to remove the following word separators and capitalize the first letter of each word it
finds (while not affecting the case of any other letters):
Let’s take a look at a few examples to see how this would format a few example strings. The
string returned will appear above the function call as a comment. In fact, all of the function calls
below will return the string MyWords:
1 use Illuminate\Support\Str;
2
3 // MyWords
4 echo Str::studly('my words');
5
6 // MyWords
7 echo Str::studly('my words');
8
9 // MyWords
10 echo Str::studly(' my-words');
11
12 // MyWords
13 echo Str::studly(' my-words_');
³https://github.com/danielstjules/Stringy
⁴https://github.com/tchwork/utf8
String Helper Functions 4
Pascal Case
Laravel’s studly method can also be used to generate Pascal Cased style strings. Both
styles are the same as camel case with the first letter capitalized.
Because the studly method does not affect the case of any letters after the first letter, we can
arrive at output that some users might not expect. Again, the output string will appear above the
method call in a comment.
1 use Illuminate\Support\Str;
2
3 // MyWORDS
4 echo Str::studly('my-WORDS');
5
6 // MYWORDS
7 echo Str::studly('MY_WORDS');
1.3.1 studly_case($value)
The studly_case function is a shortcut to calling Str::studly. This function is declared in
the global namespace.
1.4 camel($value)
Camel casing is similar to studly case such that each word starts with a capitalized letter, with the
difference being the first character is lowercased. Like the studly method, the camel method
will not affect the casing of the rest of the word.
The following examples will all return the string myWords:
1 use Illuminate\Support\Str;
2
3 // myWords
4 echo Str::camel('my words');
5
6 // myWords
7 echo Str::camel('my-words');
8
9 // myWords
10 echo Str::camel('my_words');
11
12 // myWords
13 echo Str::camel(' my-words_');
Again, the camel function does not affect the casing of any characters after the first one.
String Helper Functions 5
1 use Illuminate\Support\Str;
2
3 // mYWORDS
4 echo Str::camel('MY WORDS');
5
6 // mywords
7 echo Str::camel('mywords');
1.4.0.1 camel_case($value)
The camel_case function is a shortcut to calling Str::camel. This function is declared in the
global namespace.
Here are a few examples with the result above the function call in comments:
1 use Illuminate\Support\Str;
2
3 // my_words
4 echo Str::snake('MyWords');
5
6 // my-words
7 echo Str::snake('MyWords', '-');
8
9 // m_y_w_o_r_d_s
10 echo Str::snake('MYWORDS');
11
12 // this is _pretty_cool
13 echo Str::snake('this_is_PrettyCool');
1.6 title($value)
This method will convert the given $value to look like a traditional print title. This method
essentially will transform the entire $value to its lowercased equivalent and then uppercase
the first character of each word it finds. This method may potentially affect the case of every
character in the string.
1 use Illuminate\Support\Str;
2
3 // This Is A Title
4 echo Str::title('THIS IS A TITLE');
5
6 // This Is A Title
7 echo Str::title('this is a title');
8
9 // This Is A Title
10 echo Str::title('ThIs Is a tItle');
1.6.1 title_case($value)
The title_case helper function is a shortcut to calling Str::title. This function is declared
in the global namespace.
This function will also convert the entire string to its lowercased alternative.
String Helper Functions 7
1 use Illuminate\Support\Str;
2
3 // laravel-ninja
4 echo Str::slug('laravel ninja');
5
6 // laravel-ninja
7 echo Str::slug(' laravel ninja ');
8
9 // laravel-nin-ja
10 echo Str::slug(' Laravel NIN JA ');
11
12 // laravel-ninja
13 echo Str::slug('Laravel - Ninja - ');
14
15 // laravel-ninja
16 echo Str::slug('Laravel-_-_Ninja - ');
1 use Illuminate\Support\Str;
2
3 // These are our $needles we want to check for.
4 $needles = ['a', 'p', 'l', 'e', 's'];
5
6 // true
7 Str::contains('apples', $needles);
8
9 // false
10 Str::contains('APPLES', $needles);
11
12 // true
13 Str::contains('APPLEs', $needles);
String Helper Functions 8
1 use Illuminate\Support\Str;
2
3 // true
4 Str::endsWith('A simple sentence.', '.');
5
6 // false
7 Str::endsWith('No punctuation here', '.');
8
9 // false
10 Str::endsWith('Case matters', 'S');
11
12 // true
13 Str::endsWith('CASE STILL MATTERS', 'S');
We can combine this with PHP’s built in range⁵ function for a simple way to check if a string
ends in any alphabetical character:
1 use Illuminate\Support\Str;
2
3 // First, let's build our alphabet string.
4 $alphabet = array_merge(range('a', 'z'), range('A', 'Z'));
5
6 // true
7 Str::endsWith('This is a simple string', $alphabet);
8
9 // false
10 Str::endsWith('This ends the number 2', $alphabet);
1 use Illuminate\Support\Str;
2
3 // true
4 Str::startsWith('A simple sentence.', 'A');
5
6 // false
7 Str::startsWith('No punctuation here', '.');
8
9 // false
10 Str::startsWith('Case matters', 'c');
11
12 // true
13 Str::startsWith('CASE STILL MATTERS', 'C');
1 use Illuminate\Support\Str;
2
3 // /home/path/
4 echo Str::finish('/home/path', '/');
5
6 // /home/path/
7 echo Str::finish('/home/path/', '/');
8
9 // Sentences should end with a period, or full stop.
10 echo Str::finish('Sentences should end with a period, or full stop', '.');
11
12 // Sentences should end with a period, or full stop.
13 echo Str::finish('Sentences should end with a period, or full stop.', '.');
1 use Illuminate\Support\Str;
2
3 // this_is_a_file_path.html
4 echo Str::finish(Str::slug('this is a file path','_'), '.html');
1 use Illuminate\Support\Str;
2
3 // true
4 Str::is('word', 'word');
5
6 // true
7 Str::is('pre*', 'prepare');
8
9 // true
10 Str::is('*pare', 'prepare');
11
12 // true
13 Str::is('*pare', 'compare'));
14
15 // true
16 Str::is('m*e', 'mouse');
17
18 // true
19 Str::is('m*e', 'meme');
The following example return false, and is just to demonstrate that the is method will not
match traditional regular expressions:
String Helper Functions 11
1 use Illuminate\Support\Str;
2
3 // false
4 Str::is('[0-9]', '1');
1 use Illuminate\Support\Str;
2
3 // true
4 Str::is('[0-9]*', '[0-9] any thing');
5
6 // true
7 Str::is('[0-9]*', '[0-9][a-z]');
1.13 length($value)
The length helper method simply returns the length of the given $value, using PHP’s internal
character encoding.
1 use Illuminate\Support\Str;
2
3 // 5
4 echo Str::length('12345');
5
6 // 120
7 echo Str::length(str_repeat('n', 120));
str_repeat($input, $multiplier)
str_repeat is a function built into PHP that repeats a given $input $multiplier
number of times. So calling str_repeat('n', 120) results in a string containing 120
occurrences of the character n.
1 use Illuminate\Support\Str;
2
3 // Hello...
4 echo Str::limit('Hello world', 5);
5
6 // Hello wo...
7 echo Str::limit('Hello wo...', 8);
1 use Illuminate\Support\Str;
2
3 // Hello everyone...
4 echo Str::words('Hello everyone out there!', '2);
1.16 lower($value)
The lower helper method takes a given value and returns a lower cased variant.
1 use Illuminate\Support\Str;
2
3 // all lower cased
4 echo Str::lower('ALL LOWER CASED');
1.17 upper($value)
The upper method is the opposite of the lower method and it takes a given value and returns
the upper case variant. This method is useful when doing string comparisons.
1 use Illuminate\Support\Str;
2
3 // ALL UPPER CASED
4 echo Str::upper('all upper cased');
String Helper Functions 13
doctrine/inflector
Previous versions of Laravel managed word inflections itself. Starting with version
5, Laravel now uses the doctrine/inflector⁶ package. This package is used by the
Illuminate\Support\Pluralizer class, which is utilized by both the plural and
the singular method.
The method takes the $value that should be pluralized, and the $count of the items. If the
$count is equal to 1, the original $value is returned.
1 use Illuminate\Support\Str;
2
3 // cow
4 echo Str::plural('cow', 1);
5
6 // cows
7 echo Str::plural('cows');
8
9 // person
10 echo Str::plural('person', 1);
11
12 // people
13 echo Str::plural('person');
⁶https://github.com/doctrine/inflector
String Helper Functions 14
1 use Illuminate\Support\Str;
2
3 $messageCount = count($messages);
4
5 echo 'You have '.$messageCount.' unread '.
6 Str::plural('message',$messageCount);
If the user had one message, the above example would output:
Since the $messages array has 3 items in it, the user would see this:
In addition to words that are not inflected, the method also handles some special cases. These
are generally words that do not have a clear pragmatic method of handling the inflection of
converting the word to its plural equivalent:
1.19 singular($value)
The singular helper method is the logical opposite to the plural method: it will attempt to
take a given $value and return the singular form of that word. The internal mechanisms are
similar to the plural method.
1 use Illuminate\Support\Str;
2
3 // cow
4 echo Str::singular('cows');
5
6 // person
7 echo Str::singular('people');
8
9 // curve
10 echo Str::singular('curves');
11
12 // message
13 echo Str::singular('messages');
whiting wildebeest
In addition to words that are not inflected, the method also handles some special cases. These
are generally words that do not have a clear pragmatic method of handling the inflection of
converting the word to its singular equivalent:
1.20.1 str_singular($title)
The str_singular function is a shortcut to calling Str::singular. This function is declared
in the global namespace.
RuntimeException
A RuntimeException⁹ will be thrown if a call is made to random without the OpenSSL
extension installed.
It should also be noted that the random method remove the following characters:
/ + =
The following examples show sample output. Because the intention of the random method is to
generate a random string, any output you get will likely be different:
1 use Illuminate\Support\Str;
2
3 // XHJtXFOa5Jt8B48z
4 echo Str::random();
5
6 // z50fdgeBrmoJRBh7
7 echo Str::random();
8
9 // 2bXJNUcZVdtZfUUzbEgfvvaawOCfOgvK
10 echo Str::random(32);
While the quickRandom function is useful for fast generation of random strings (for
use in URI’s, tokens, etc), , it should not be used in instances where cryptographically
secure strings are required.
1 use Illuminate\Support\Str;
2
3 // LDM03NP6upx1NUMt
4 echo Str::quickRandom();
5
6 // jlxyb2YBCxPLZ6OL
7 echo Str::quickRandom();
8
9 // rlLdOd0YIWZxdmTZMBkItbsduCNUKck2
10 echo Str::quickRandom(32);
1 use \Illuminate\Support\Str;
2
3 // true
4 Str::equals('test string', 'test string');
5
6 // true
7 Str::equals('', '');
8
9 // false
10 Str::equals('AAA', 'aaa');
11
12 // true
13 Str::equals(hash('sha256', md5('test')), hash('sha256', md5('test')));
As of Laravel version 5.2, the previous internal implementation of the equals helper
method has been deprecated in favor of PHP’s built in hash_equals¹⁰ function.
• http://php.net/manual/en/function.hash-equals.php¹¹
• https://en.wikipedia.org/wiki/Time_complexity#Constant_time¹²
• http://blog.ircmaxell.com/2014/11/its-all-about-time.html¹³
• http://security.stackexchange.com/questions/49849/timing-safe-string-comparison-avoiding-
length-leak¹⁴
1 ClassName@someMethodName
The point is that there is a string, split by the @ symbol, with the class name on the left and a
method name on the right. We can use the parseCallback method to break up this string, and
also specify a $default method name. If there is nothing on the right hand side of the @ symbol,
or if there is no @ symbol, the $default is used as the returned method name.
The function returns an array, with two elements. The first element is the class name, and the
second element will be the method name.
The following examples will highlight the values that might be returned from this function:
1 use Illuminate\Support\Str;
2
3 Str::parseCallback('MyClass', 'defaultValue');
1 array(2) {
2 [0] "MyClass"
3 [1] "defaultValue"
4 }
1 use Illuminate\Support\Str;
2
3 Str::parseCallback('MyClass@method', 'defaultValue');
1 array(2) {
2 [0] "MyClass"
3 [1] "method"
4 }
1 use Illuminate\Support\Str;
2
3 Str::parseCallback('MyClass@method@somethingElse', 'defaultValue');
1 array(2) {
2 [0] "MyClass"
3 [1] "method@somethingElse"
4 }
It is with this example that it becomes obvious that the parseCallback will only observe the
first @ symbol. Anything after the first occurance of the @ symbol will become part of the method
name returned.
1 use Illuminate\Support\Str;
2
3 Str::parseCallback('', '');
1 array(2) {
2 [0] ""
3 [1] ""
4 }
1 use Illuminate\Support\Str;
2
3 class MyClass {
4
5 /**
6 * Returns a hello message.
7 *
8 * @return string
9 */
10 public static function sayHello()
11 {
12 return 'Hello';
13 }
14
15 }
16
17 // Would send 'Hello' to the screen.
18 echo call_user_func(Str::parseCallback('MyClass@sayHello'));
String Helper Functions 23
1 use Illuminate\Support\Str;
2
3 // //maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
4 Str::replaceFirst(
5 'http://', '//',
6 'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
7 );
8
9 // Hello, there!
10 Str::replaceFirst('there', 'Hello', 'there, there!');
1 use Illuminate\Support\Str;
2
3 // Hello! Goodbye!
4 Str::replaceLast('Hello', 'Goodbye', 'Hello! Hello!');
5
6 // Super long content. Another sentence. Final sentence∎
7 Str::replaceLast(
8 '.', '∎',
9 'Super long content. Another sentence. Final sentence.'
10 );
String Helper Functions 24
substr Encoding
PHP’s mb_substr¹⁶ function allows you to change the encoding that is used when
extracting the substring from the string. Laravel’s substr helper method always uses
the UTF-8 encoding when making its call to the mb_substr function.
The following examples highlight the usage of the substr helper method. An example string
of 01213456789 will be used so that the substring will be easer to identify. The results of the
function call will appear above the call as a comment.
1 use Illuminate\Support\Str;
2
3 // Create a testing string.
4 $testString = '0123456789';
5
6 // 56789
7 Str::substr($testString, 5);
8
9 // 6789
10 Str::substr($testString, 6);
11
12 // 67
13 Str::substr($testString, 6, 2);
¹⁵http://php.net/manual/en/function.mb-substr.php
¹⁶http://php.net/manual/en/function.mb-substr.php
String Helper Functions 25
14
15 // 89
16 Str::substr($testString, -2);
17
18 // 8
19 Str::substr($testString, -2, 1);
1.29 ucfirst($string)
The ucfirst helper method is used to uppercase the first letter of a string. It defines only one
parameter—$string—which is the string that should have it’s first letter uppercased. This helper
method differs from PHP’s ucfirst¹⁷ function because the Laravel helper method handles multi-
byte strings by reimplementing the ucfirst function using PHP’s multibyte string API.
The following example demonstrates the usage of the ucfirst helper method:
1 use Illuminate\Support\Str;
2
3 // A simple string to work with.
4 $testString = 'this is a sentence.';
5
6 // This is a sentence.
7 $uppercased = Str::ucfirst($testString);
The ucfirst helper method can be quite useful when combined with the finish helper method.
For example, we can combine these two methods to ensure the that a sentence starts with an
uppercased letter and ends with a period (or full stop):
1 use Illuminate\Support\Str;
2
3 // This is a sentence.
4 $firstValue = Str::finish(Str::ucfirst('this is a sentence'), '.');
5
6 // This is a sentence.
7 $secondValue = Str::finish(Str::ucfirst('this is a sentence.'), '.');
The trans helper function is used to return the translation for the given key. It defines a $key
parameter which corresponds to an array key within the group file. It also accepts an array
¹⁷http://php.net/manual/en/function.ucfirst.php
String Helper Functions 26
of replacements (which are passed through the $parameters array parameter) and a $locale
parameter, which can be used to specify the desired locale.
Replacements are passed as a key/value pair. The replacement keys will be matched to any
placeholders within the translation. Placeholders begin with a single colon (:) followed by a
name and a space. For example, in the validation.php language file, the following lines can
be found:
1 <?php
2
3 return [
4
5 ...
6
7 'accepted' => 'The :attribute must be accepted.',
8 'array' => 'The :attribute must be an array.',
9
10 ...
11
12 ];
In the above translation lines, :attribute is a placeholder than can be replaced using the
$parameters parameter. The following code examples will demonstrate the results of using
the $parameters parameter. The results will appear above the method call as a comment.
It should be noted that the placeholder name in the $parameters parameter should not contain
the leading : character.
The trans_choice helper function is used to pluralize a given $id, translating it for the given
$locale. The choice method accepts the $number of some collection of objects that it should
use when making pluralization decisions. Like the trans helper function, it also accepts and
array of replacements, using the $parameters array.
Assuming the following group file is located at /resource/lang/en/plural.php:
String Helper Functions 27
1 <?php
2
3 return [
4 'books' => 'There is one book.|There are :count many books.',
5 ];
It should be noted that pluralized strings allow for multiple messages to be stored in one
translation line. Messages are separated by the | character, and are ordered such that the message
that corresponds to the lower $number appear first and messages that appear for any higher
$number appear sequentially afterwards.
The following code example would select the first message:
The following code examples highlight some more ways the trans_choice helper function can
be called, and ways they will mostly appear within applications:
1.32 e($value)
The e function is a simple wrapper of PHP’s htmlentities function. The e function utilizes
the UTF-8 character encoding. The e function will sanitize user input when displaying it to the
browser.
Let’s assume that a malicious user was posting on a forum and set the subject of their post to
this:
1 <script>alert("hello everyone");</script>
If the forum software did not sanitize user output, perfectly valid JavaScript code would be
sent to the browser. Since browsers are overly happy to execute any JavaScript included in the
document, any forum visitor would see an alert box with hello everyone every time a page
was loaded that displayed that particular forum post.
To prevent this, use the e function to sanitize user input when sending it to the browser:
String Helper Functions 28
1 <script>alert("hello everyone");</script>gt;
At this point the browser will render a string that literally represents what they had typed.
2. Array Helper Functions
Laravel provides many helper functions for interacting and manipulating array data structures.
Laravel’s array functions offer additional functionality on top of PHP’s built in array functions.
The helper functions in this section are located within the Illuminate\Support\Arr static
class. There are functions defined in the static class that have counterparts defined in the global
namespace. These functions appear below each static function.
1 use Illuminate\Support\Arr;
2
3 $originalArray = [
4 'fruit' => 'orange',
5 'vegetable' => 'carrot'
6 ];
7
8 $anotherArray = array_add($originalArray, 'vehicle', 'car');
1 array(2) {
2 ["fruit"] "orange"
3 ["vegetable"] "carrot"
4 }
This is because Laravel’s functions do not affect the original array (unless stated otherwise).
Running var_dump on $anotherArray, however, would produce the expected results:
29
Array Helper Functions 30
1 array(3) {
2 ["fruit"] "orange"
3 ["vegetable"] "carrot"
4 ["vehicle"] "car"
5 }
1 forms = document.forms;
1 use Illuminate\Support\Arr;
2
3 // Create a multi-dimensional array, to simulate a document and forms.
4 $testDocument = [
5 'document' => [
6 'forms' => [
7
8 ]
9 ]
10 ];
11
12 // Get the forms.
13 $forms = Arr::get($testDocument, 'document.forms');
14
15 // Traditionally, with vanilla PHP:
16 $forms = $testDocument['document']['forms'];
Using dot notation with Laravel’s functions will be explored in more detail in the following
sections.
1 use Illuminate\Support\Arr;
2
3 $myArray = [
4 'animal' => 'Araripe Manakin',
5 'plant' => 'Pineland Wild Petunia'
6 ];
7
8 $myArray = Arr::add($myArray, 'insect', 'Extatosoma Tiaratum');
1 array(3) {
2 ["animal"] "Araripe Manakin"
3 ["plant"] "Pineland Wild Petunia"
4 ["insect"] "Extatosoma Tiaratum"
5 }
1 use Illuminate\Support\Arr;
2
3 $myArray = [
4 'animal' => 'Araripe Manakin',
5 'plant' => 'Pineland Wild Petunia'
6 ];
7
8 $myArray = Arr::build($myArray, function($key, $value)
9 {
10 return [$key, $value.' is rare'];
11 });
1 array(2) {
2 ["animal"] "Araripe Manakin is rare"
3 ["plant"] "Pineland Wild Petunia is rare"
4 }
2.5 divide($array)
The divide helper method will take the given $array and create two new arrays. The first array
will be all of the keys from the original $array and the second array will be all of the values.
1 use Illuminate\Support\Arr;
2
3 $myArray = [
4 'animal' => 'Araripe Manakin',
5 'plant' => 'Pineland Wild Petunia'
6 ];
7
8 $myArray = Arr::divide($myArray);
1 array(2) {
2 [0] array(2) {
3 [0] "animal"
4 [1] "plant"
5 }
6 [1] array(2) {
7 [0] "Araripe Manakin"
8 [1] "Pineland Wild Petunia"
9 }
10 }
2.5.1 array_divide($array)
The array_divide function is a shortcut to calling Arr::divide. This function is declared in
the global namespace.
Array Helper Functions 33
2.6 collapse($array)
The collapse helper method accepts an array as its only parameter. The given $array can be a
single array, or a nested array. The method will then return a new array with the contents of all
the nested arrays. Arrays that are collapsed can contain any data type, such as integers, string
literals, objects and other arrays. The examples that follow will use integers in all arrays.
Assuming the following array and example:
1 use \Illuminate\Support\Arr;
2
3 $testArray = [
4 [
5 1,2,3,4
6 ],
7 [
8 5,6,7,8,
9 ]
10 ];
11
12 $collapsedArray = Arr::collapse($testArray);
1 array (size=8)
2 0 => int 1
3 1 => int 2
4 2 => int 3
5 3 => int 4
6 4 => int 5
7 5 => int 6
8 6 => int 7
9 7 => int 8
It is important to note that the collapse method is not recursive. This can be observed in the
following example:
Array Helper Functions 34
1 use \Illuminate\Support\Arr;
2
3 $testArray = [
4 [
5 1,2,3,4
6 ],
7 [
8 5,6,7,8,
9 [
10 9,10,11,12
11 ]
12 ]
13 ];
14
15 $collapsedArray = Arr::collapse($testArray);
1 array (size=9)
2 0 => int 1
3 1 => int 2
4 2 => int 3
5 3 => int 4
6 4 => int 5
7 5 => int 6
8 6 => int 7
9 7 => int 8
10 8 =>
11 array (size=4)
12 0 => int 9
13 1 => int 10
14 2 => int 11
15 3 => int 12
1 use \Illuminate\Support\Arr;
2 use \Illuminate\Support\Collection;
3
4 $testArray = [
5 new Collection([1,2,3,4]),
6 new Collection([5,6,7,8])
7 ];
8
9 $collapsedArray = Arr::collapse($testArray);
1 array (size=8)
2 0 => int 1
3 1 => int 2
4 2 => int 3
5 3 => int 4
6 4 => int 5
7 5 => int 6
8 6 => int 7
9 7 => int 8
1 use \Illuminate\Support\Arr;
2 use \Illuminate\Support\Collection;
3
4 $testArray = new Collection([
5 new Collection([1,2,3,4]),
6 [5,6,7,8]
7 ]);
8
9 $collapsedArray = Arr::collapse($testArray);
1 array (size=8)
2 0 => int 1
3 1 => int 2
4 2 => int 3
5 3 => int 4
6 4 => int 5
7 5 => int 6
8 6 => int 7
9 7 => int 8
2.6.2 array_collapse($array)
The array_collapse function is a shortcut to calling Arr::collapse. This function is declared
in the global namespace.
1 use Illuminate\Support\Arr;
2
3 $myArray = [
4 'user' => [
5 'first_name' => 'John',
6 'last_name' => 'Doe',
7 'career' => [
8 'name' => 'Programmer',
9 'description' => 'Make stuffs.'
10 ]
11 ]
12 ];
13
14 $myArray = Arr::dot($myArray);
1 array(4) {
2 ["user.first_name"] "John"
3 ["user.last_name"] "Doe"
4 ["user.career.name"] "Programmer"
5 ["user.career.description"] "Make stuffs."
6 }
The dot method also accepts a value for $prepend which will be added to the beginning of all
the newly generated keys. Executing the following:
Array Helper Functions 37
1 array(4) {
2 ["prepended_user.first_name"] "John"
3 ["prepended_user.last_name"] "Doe"
4 ["prepended_user.career.name"] "Programmer"
5 ["prepended_user.career.description"] "Make stuffs."
6 }
1 array(3) {
2 ["first_name"] "John"
3 ["last_name"] "Doe"
4 ["password"] "some_password"
5 }
We could easily get all the information except for the password like so:
1 use Illuminate\Support\Arr;
2
3 $inputData = Arr::except($_POST, 'password');
1 array(2) {
2 ["first_name"] "John"
3 ["last_name"] "Doe"
4 }
When passing a single item, such as password, for the $keys parameter, it will be
converted to an array automatically.
1 use Illuminate\Support\Arr;
2
3 // This would only return an array with the user's `last_name`.
4 $inputData = Arr::except($_POST, ['password', 'first_name']);
1 use Illuminate\Support\Arr;
2
3 $inputData = Arr::only($_POST, 'first_name');
1 array(1) {
2 ["first_name"] "John"
3 }
2.10 flatten($array)
The flatten helper method is similar to the dot method in that it takes a multi-dimensional
array and transforms it into a new array with only one dimension. While the dot method
preserves the keys by separating them with dots, the flatten method will create a new array
containing the original array’s data whilst throwing away the array’s keys.
Consider the following array:
Array Helper Functions 39
1 $arrayToFlatten = [
2 'keys' => 'first value',
3 'will' => 'second value',
4 'be' => 'third value',
5 'removed' => 'fourth value'
6 ];
1 $newArray = Arr::flatten($arrayToFlatten);
1 array(4) {
2 [0] "first value"
3 [1] "second value"
4 [2] "third value"
5 [3] "fourth value"
6 }
2.10.1 array_flatten($array)
The array_flatten function is a shortcut to calling Arr::flatten. This function is declared
in the global namespace.
Deprecated
The fetch helper function has been deprecated as of Laravel 5.1 in favor of the pluck
helper function.
The fetch helper method is used to pull data from a multi-dimensional array. The data to fetch
is expressed in dot notation. Assuming the following array of students, languages and courses:
Array Helper Functions 40
1 $students = [
2 'student-001' => [
3 'first_name' => 'John',
4 'languages' => [
5 'count' => 2,
6 'names' => [
7 'French',
8 'English'
9 ]
10 ],
11 'courses' => [
12 'CIS 100',
13 'CIS 200'
14 ]
15 ],
16 'student-002' => [
17 'first_name' => 'Jane',
18 'languages' => [
19 'count' => 2,
20 'names' => [
21 'Spanish',
22 'English'
23 ]
24 ],
25 'courses' => [
26 'CIS 100',
27 'CIS 200'
28 ]
29 ],
30 'student-003' => [
31 'first_name' => 'Jim',
32 'courses' => [
33 'HUMA 1302'
34 ]
35 ]
36 ];
1 use Illuminate\Support\Arr;
2
3 $courses = Arr::fetch($students, 'courses');
1 array(3) {
2 [0] array(2) {
3 [0] "CIS 100"
4 [1] "CIS 200"
5 }
6 [1] array(2) {
7 [0] "CIS 100"
8 [1] "CIS 200"
9 }
10 [2] array(1) {
11 [0] "HUMA 1302"
12 }
13 }
Accessing the count value within the languages array can be done using dot notation:
1 use Illuminate\Support\Arr;
2
3 $languageCounts = Arr::fetch($students, 'languages.count');
1 array(2) {
2 [0] 2
3 [1] 2
4 }
When an array key is specified that does not exist in one of the nested arrays, no value
is returned. That is why there is only two student language counts in the above array
when there are three students.
Accessing all the languages spoken by the students could be done like so:
1 use Illuminate\Support\Arr;
2
3 $languages = Arr::fetch($students, 'languages.names');
1 array(2) {
2 [0] array(2) {
3 [0] "French"
4 [1] "English"
5 }
6 [1] array(2) {
7 [0] "Spanish"
8 [1] "English"
9 }
10 }
1 $languages = Arr::flatten($languages);
1 array(4) {
2 [0] "French"
3 [1] "English"
4 [2] "Spanish"
5 [3] "English"
6 }
1 $languages = array_unique($languages);
1 array(3) {
2 [0] "French"
3 [1] "English"
4 [2] "Spanish"
5 }
http://php.net/manual/en/function.array-unique.php
Array Helper Functions 43
Let’s begin discussing the first helper method be examining the $callback. The $callback
is a function that accepts a $key and a $value as it’s parameters. The following code sample is
an anonymous function assigned to a variable named $isPostFormat. This function will use
the Str::is helper method to check if a value is of the format /post/*:
1 use Illuminate\Support\Str;
2
3 $isPostFormat = function($key, $value) {
4 return Str::is('/post/*', $value);
5 };
If a given value satisfies the format, true is returned, otherwise false is returned.
This would return true:
1 $isPostFormat('key', '/post/array_first');
1 $isPostFormat('key', 'not-a-post');
So how does this work with the first function? Consider the following array:
1 $sampleArray = [
2 'browser',
3 'headphones',
4 '/post/a-post-format',
5 'something else'
6 ];
We can call first function and pass our callback function as a parameter like so:
Array Helper Functions 44
1 use Illuminate\Support\Arr;
2
3 $firstPost = Arr::first($sampleArray, $isPostFormat);
The first function will iterate over every item in the array and apply our $callback function
to each item. The first key/value pair to return true from the $callback function is returned
as the value. Therefore, $firstPost would have the value of /post/a-post-format.
It is possible that no key/value pair will satisfy the callback function. To account for this, a
$default value can be specified. The default value for the $default value is null. Consider
the following array which has no valid post formats (according to our $isPostFormat function):
1 $sampleArray = [
2 'browser',
3 'headphones',
4 'not-a-post-format',
5 'something else'
6 ];
the same code from earlier would return null instead of /post/a-post-format:
1 use Illuminate\Support\Arr;
2
3 $firstPost = Arr::first($sampleArray, $isPostFormat);
The default value can be changed by passing a third argument to the first function:
1 use Illuminate\Support\Arr;
2
3 $firstPost = Arr::first($sampleArray, $isPostFormat, '/post/this-is-my-defaul\
4 t-value');
1 use Illuminate\Support\Arr;
2
3 // 'browser'
4 $firstItem = Arr::first($sampleArray);
The last helper method is the logical opposite of the first method. The difference is that the
last function will return the last value to satisfy the $callback function. If no value is returned
from the $callback function, the $default value is returned.
Using the same $isPostFormat function from the first section:
1 use Illuminate\Support\Str;
2
3 $isPostFormat = function($key, $value) {
4 return Str::is('/post/*', $value);
5 };
we could get the last post in the following array like so:
1 use Illuminate\Support\Arr;
2
3 $postsArray = [
4 '/post/first-post',
5 '/post/second-post',
6 '/post/last-post'
7 ];
8
9 $lastPost = Arr::last($postsArray, $isPostFormat);
1 use Illuminate\Support\Arr;
2
3 // 'something else'
4 $firstItem = Arr::last($sampleArray);
1 $anArray = [
2 'nested_array_one' => [
3 'nested_array_two' => [
4 'key' => 'value'
5 ]
6 ]
7 ];
1 use Illuminate\Support\Arr;
2
3 $doesExist = Arr::has($anArray, 'nested_array_one.nested_array_two.key');
Because the nested key key does in fact exist, the value of $doesExist would be true. Inversely,
we can prove that a key of does_not_exist does not, in fact, exist:
1 use Illuminate\Support\Arr;
2
3 $doesExist = Arr::has($anArray, 'does_not_exist');
Mutable Function
This function affects the original $array.
The set method also uses dot notation for its $key value. We will use the set function to create
a simple array:
1 use Illuminate\Support\Arr;
2
3 // Create an empty array to work with.
4 $testArray = [];
5
6 Arr::set($testArray, 'person.first_name', 'Jane');
7 Arr::set($testArray, 'person.last_name', 'Doe');
1 array(1) {
2 ["person"] array(2) {
3 ["first_name"] "Jane"
4 ["last_name"] "Doe"
5 }
6 }
1 array(1) {
2 ["person"] array(2) {
3 ["first_name"] "John"
4 ["last_name"] "Doe"
5 }
6 }
1 $testArray = [
2 'first' => 'element',
3 'second' => 'element'
4 ];
1 $newArray = [
2 'third' => 'element',
3 'fourth' => 'element'
4 ];
1 use Illuminate\Support\Arr;
2
3 Arr::set($testArray, null, $newArray);
1 array(2) {
2 ["third"] "element"
3 ["fourth"] "element"
4 }
1 use Illuminate\Support\Arr;
2
3 $testArray = Arr::set($testArray, null, null);
1 use Illuminate\Support\Arr;
2
3 $testArray = Arr::set($testArray, null, 100);
Mutable Function
This function affects the original $array.
1 use Illuminate\Support\Arr;
2
3 $anArray = [
4 'person' => [
5 'first_name' => 'Jane',
6 'last_name' => 'Doe'
7 ]
8 ];
1 Arr::($anArray, 'person.first_name');
1 array(1) {
2 ["person"] array(1) {
3 ["last_name"] "Doe"
4 }
5 }
Removing multiple items at once is as simple as passing an array as the second argument:
1 $anArray = [
2 'nested_array_one' => [
3 'nested_array_two' => [
4 'key' => 'value'
5 ]
6 ]
7 ];
1 use Illuminate\Support\Arr;
2
3 $value = Arr::get($anArray, 'nested_array_one.nested_array_two.key');
1 $value = $anArray['nested_array_one']['nested_array_two']['key'];
While PHP’s array access syntax may be a little shorter, using the dot notation is easier to read.
We can also specify a $default value, which will be returned if there is no matching $key found
in the array.
Array Helper Functions 51
1 use Illuminate\Support\Arr;
2
3 $value = Arr::get(
4 $anArray,
5 'nested_array_one.nested_array_two.does_not_exist',
6 'default value'
7 );
$value would then have the value of default value. Using this method is shorter than using
PHP’s array access syntax and the isset function, where we would have to check at each level
if the key exists or not.
Mutable Function
This function affects the original $array.
Consider the following array, which is probably familiar to most people these days:
1 $weekDays = [
2 1 => 'Sunday',
3 2 => 'Monday',
4 3 => 'Tuesday',
5 4 => 'Wednesday',
6 5 => 'Thursday',
7 6 => 'Friday',
8 7 => 'Saturday'
9 ];
A lot of people do not like Mondays. Let’s demote Monday to the $theWorstDayOfTheWeek
while also removing it from our $weekDays:
Array Helper Functions 52
1 use Illuminate\Support\Arr;
2
3 // Demote 'Monday'
4 $worstDayOfTheWeek = Arr::pull($weekDays, 2);
1 array(6) {
2 [1] "Sunday"
3 [3] "Tuesday"
4 [4] "Wednesday"
5 [5] "Thursday"
6 [6] "Friday"
7 [7] "Saturday"
8 }
1 class Person {
2
3 public $firstName = '';
4
5 public $lastName = '';
6
7 public function __construct($firstName, $lastName)
8 {
9 $this->firstName = $firstName;
10 $this->lastName = $lastName;
11 }
12
13 }
1 $people = [
2 new Person('Jane', 'Carter'),
3 new Person('John', 'Doe'),
4 new Person('Jack', 'Smith')
5 ];
At this point all we have is a simple Person class definition an array of person objects, called
$people. However, it would be really useful if we had an array of everyone’s last name. This is
a perfect use case for the pluck method:
1 use Illuminate\Support\Arr;
2
3 $lastNames = Arr::pluck($people, 'lastName');
1 array(3) {
2 [0] "Carter"
3 [1] "Doe"
4 [2] "Smith"
5 }
The pluck function will also work on array of arrays. Consider an array of the same people,
represented instead by arrays:
1 $justArrays = [
2 ['firstName' => 'Jane', 'lastName' => 'Carter'],
3 ['firstName' => 'John', 'lastName' => 'Doe'],
4 ['firstName' => 'Jack', 'lastName' => 'Smith']
5 ];
We could again get an array of all the last names, just like before:
1 use Illuminate\Support\Arr;
2
3 $lastNames = Arr::pluck($justArrays, 'lastName');
1 array(3) {
2 [0] "Carter"
3 [1] "Doe"
4 [2] "Smith"
5 }
1 $people = [
2 new Person('Jane', 'Carter'),
3 new Person('John', 'Doe'),
4 new Person('Jack', 'Smith')
5 ];
We can get an array with everyone’s firstName as the key, and their lastName as the value
like so:
1 use Illuminate\Support\Arr;
2
3 $peopleList = Arr::pluck($people, 'lastName', 'firstName');
1 array(3) {
2 ["Jane"] "Carter"
3 ["John"] "Doe"
4 ["Jack"] "Smith"
5 }
This can be reversed, so that the lastName becomes the key and the firstName becomes the
value:
1 use Illuminate\Support\Arr;
2
3 $peopleList = Arr::pluck($people, 'firstName', 'lastName');
1 array(3) {
2 ["Carter"] "Jane"
3 ["Doe"] "John"
4 ["Smith"] "Jack"
5 }
1 class Job {
2
3 public $name = '';
4
5 public function __construct($name)
6 {
7 $this->name = $name;
8 }
9
10 }
Now we will modify our Person class to accept a Job as one of its parameters:
1 class Person {
2
3 public $firstName = '';
4
5 public $lastName = '';
6
7 public $job = null;
8
9 public function __construct($firstName, $lastName, Job $job)
10 {
11 $this->firstName = $firstName;
12 $this->lastName = $lastName;
13 $this->job = $job;
14 }
15
16 }
After all of this work, let’s build a new array of people, this time with jobs:
Array Helper Functions 56
1 $people = [
2 new Person('Jane', 'Carter', new Job('Senior Developer')),
3 new Person('John', 'Doe', new Job('Junior Developer')),
4 new Person('Jack, 'Smith', new Job('Marketing Manager'))
5 ];
After all of this work, we now have an array that looks like this:
1 array(3) {
2 [0] object(Person)#138 (3) {
3 ["firstName"] "Jane"
4 ["lastName"] "Carter"
5 ["job"] object(Job)#139 (1) {
6 ["name"] "Senior Developer"
7 }
8 }
9 [1] object(Person)#140 (3) {
10 ["firstName"] "John"
11 ["lastName"] "Doe"
12 ["job"] object(Job)#141 (1) {
13 ["name"] "Junior Developer"
14 }
15 }
16 [2] object(Person)#142 (3) {
17 ["firstName"] "Jack"
18 ["lastName"] "Smith"
19 ["job"] object(Job)#143 (1) {
20 ["name"] "Marketing Manager"
21 }
22 }
23 }
What we want to do now is return an array where the job name is the key, and the person’s first
name is the value. Let’s call this array $filledPositions:
1 use Illuminate\Support\Arr;
2
3 $filledPositions = Arr::pluck($people, 'firstName', 'job.name');
Notice that this time the value for $key is expressed in dot notation. This will produce the
following results:
Array Helper Functions 57
1 array(3) {
2 ["Senior Developer"] "Jane"
3 ["Junior Developer"] "John"
4 ["Marketing Manager"] "Jack"
5 }
An array of all numbers less than or equal to 10 can be created like so:
1 use Illuminate\Support\Arr;
2
3 $smallNumbers = Arr::where($numbers, function($key, $value)
4 {
5 return ($value <= 10);
6 });
1 array(11) {
2 [0] 0
3 [1] 1
4 [2] 2
5 [3] 3
6 [4] 4
7 [5] 5
8 [6] 6
9 [7] 7
10 [8] 8
11 [9] 9
12 [10] 10
13 }
1 $testScores = [
2 'Alice' => 95,
3 'Allison' => 96,
4 'Bob' => 92,
5 'Delbert' => 72,
6 'Dennis' => 87,
7 'Tonya' => 32
8 ];
Let’s assume that any test score below a 70 is a failing grade. What we want to do is get an array
of everyone who has passed the test, but whose name starts with the letter a:
1 use Illuminate\Support\Arr;
2 use Illuminate\Support\Str;
3
4 $studentsWhoPassed = Arr::where($testScores, function($student, $testScore)
5 {
6 return (Str::startsWith(Str::upper($student), 'A') && $testScore >= 70);
7 });
1 array(2) {
2 ["Alice"] 95
3 ["Allison"] 96
4 }
1 $suspendedStudents = [
2 'Dennis',
3 'Tonya'
4 ];
Now we want to get only the test scores of those students who are not currently suspended
(students who are suspended to not get their test scores credited, and instead receive a 0 mark):
1 $validTestScores = Arr::where($testScores,
2 function($student, $testScore)
3 use ($suspendedPeople)
4 {
5 return (!Arr::has(array_flip($suspendedPeople), $student));
6 });
1 array(4) {
2 ["Alice"] 95
3 ["Allison"] 96
4 ["Bob"] 92
5 ["Delbert"] 72
6 }
1 class StudentTestResult {
2
3 public $name = '';
4
5 public $testScore = '';
6
7 public function __construct($name, $testScore)
8 {
9 $this->name = $name;
10 $this->testScore = $testScore;
11 }
12
13 }
1 $testScores = [
2 new StudentTestResult('Alice', 95),
3 new StudentTestResult('Allison', 96),
4 new StudentTestResult('Bob', 92),
5 new StudentTestResult('Delbert', 72),
6 new StudentTestResult('Dennis', 87),
7 new StudentTestResult('Tonya', 32)
8 ];
1 array(6) {
2 [0] object(StudentTestResult)#138 (2) {
3 ["name"] "Alice"
4 ["testScore"] 95
5 }
6 [1] object(StudentTestResult)#139 (2) {
7 ["name"] "Allison"
8 ["testScore"] 96
9 }
10 [2] object(StudentTestResult)#140 (2) {
11 ["name"] "Bob"
12 ["testScore"] 92
13 }
14 [3] object(StudentTestResult)#141 (2) {
15 ["name"] "Delbert"
16 ["testScore"] 72
17 }
18 [4] object(StudentTestResult)#142 (2) {
19 ["name"] "Dennis"
20 ["testScore"] 87
21 }
22 [5] object(StudentTestResult)#143 (2) {
23 ["name"] "Tonya"
24 ["testScore"] 32
25 }
26 }
We want to see the students that have the worst test scores first, so that we can offer them extra
help, or just to see what’s going on:
Array Helper Functions 62
1 use Illuminate\Support\Arr;
2
3 $sortedScores = Arr::sort($testScores, function($student)
4 {
5 // Sort the student's scores by their test score.
6 return $student->testScore;
7 });
1 array(6) {
2 [5] object(StudentTestResult)#143 (2) {
3 ["name"] "Tonya"
4 ["testScore"] 32
5 }
6 [3] object(StudentTestResult)#141 (2) {
7 ["name"] "Delbert"
8 ["testScore"] 72
9 }
10 [4] object(StudentTestResult)#142 (2) {
11 ["name"] "Dennis"
12 ["testScore"] 87
13 }
14 [2] object(StudentTestResult)#140 (2) {
15 ["name"] "Bob"
16 ["testScore"] 92
17 }
18 [0] object(StudentTestResult)#138 (2) {
19 ["name"] "Alice"
20 ["testScore"] 95
21 }
22 [1] object(StudentTestResult)#139 (2) {
23 ["name"] "Allison"
24 ["testScore"] 96
25 }
26 }
1 use Illuminate\Support\Arr;
2
3 $sortedScores = Arr::sort($testScores, function($student)
4 {
5 // Sort the student's scores by their name.
6 return $student->name;
7 });
1 array(6) {
2 [0] object(StudentTestResult)#138 (2) {
3 ["name"] "Alice"
4 ["testScore"] 95
5 }
6 [1] object(StudentTestResult)#139 (2) {
7 ["name"] "Allison"
8 ["testScore"] 96
9 }
10 [2] object(StudentTestResult)#140 (2) {
11 ["name"] "Bob"
12 ["testScore"] 92
13 }
14 [3] object(StudentTestResult)#141 (2) {
15 ["name"] "Delbert"
16 ["testScore"] 72
17 }
18 [4] object(StudentTestResult)#142 (2) {
19 ["name"] "Dennis"
20 ["testScore"] 87
21 }
22 [5] object(StudentTestResult)#143 (2) {
23 ["name"] "Tonya"
24 ["testScore"] 32
25 }
26 }
1 use Illuminate\Support\Arr;
2
3 // false
4 $isAssoc = Arr::isAssoc([0,1,2,3]);
5
6 // false
7 $isAssoc = Arr::isAssoc([1,2,3,4]);
8
9 // false
10 $isAssoc = Arr::isAssoc([2,3,4,6]);
11
12 // true
13 $isAssoc = Arr::isAssoc([
14 'associative' => 'array'
15 ]);
16
17 // false
18 $isAssoc = Arr::isAssoc([
19 0 => 'A',
20 1 => 'B',
21 2 => 'C'
22 ]);
Array Helper Functions 65
2.23 accessible($value)
The accessible helper method is used to determine whether the given $value is array
accessible. A value $value is array accessible if the value is an array or an instance of
ArrayAccess¹.
The following examples demonstrate the usage of the accessible helper method. The results
of the method call appear above the call as a comment:
Any value that returns true from the Arr::accessible helper method can be used
as a value for $array.
The following examples demonstrate the usage of the exists method. The results of the method
call will appear above the call as a comment.
¹http://php.net/manual/en/class.arrayaccess.php
²http://php.net/manual/en/function.array-key-exists.php
Array Helper Functions 66
1 use Illuminate\Support\Arr;
2
3 // Create some test data to work with.
4 $array = [
5 'first_name' => 'Jane',
6 'last_name' => 'Doe'
7 ];
8
9 $collection = collect($array);
10 $model = factory('App\User')->make();
11
12 // true
13 Arr::exists($array, 'first_name');
14 Arr::exists($array, 'last_name');
15
16 // false
17 Arr::exists($array, 'middle_name');
18
19 // true
20 Arr::exists($collection, 'first_name');
21 Arr::exists($collection, 'last_name');
22
23 // false
24 Arr::exists($collection, 'middle_name');
25
26 // true
27 Arr::exists($model, 'name');
28 Arr::exists($model, 'email');
29 Arr::exists($model, 'remember_token');
30
31 // false
32 Arr::exists($model, 'first_name');
1 use Illuminate\Support\Arr;
2
3 // Create an array to work with.
4 $array = [
5 'first_name' => 'Jane',
6 'last_name' => 'Doe'
7 ];
8
9 // Add a new item to the beginning of the array.
10 $array = Arr::prepend($array, 26, 'id');
After the above code has executed, the $array variable would contain a value similar to the
following output:
1 array:3 [
2 "id" => 26
3 "first_name" => "Jane"
4 "last_name" => "Doe"
5 ]
The following example shows the usage of the prepend method without supplying an argument
for the $key parameter:
1 use Illuminate\Support\Arr;
2
3 // Create an array to work with.
4 $array = ['the', 'community'];
5
6 // Add a new item to the beginning of the array.
7 $array = Arr::prepend($array, 'for');
After the above code has executed, the $array variable would contain a value similar to the
following output:
1 array:3 [
2 0 => "for"
3 1 => "the"
4 2 => "community"
5 ]
The app function can also be used to resolve registered dependencies from the Container
instance. For example, to return an instance of the Illuminate\Auth\AuthManager class (the
class behind the Auth facade), invoke app with the auth argument:
The following example shows to equivalent ways of retrieving the currently logged in user:
1 use Illuminate\Support\Facades\Auth;
2
3 // Get the current user using the `Auth` facade.
4 $currentUser = Auth::user();
5
6 // Get the current user using the `auth` helper.
7 $currentUser = auth()->user();
You can quickly access any custom authentication guards by supplying an argument for the
$guard parameter. For example if a custom guard was added with the name customGuard:
68
Application and User Flow Helper Functions 69
1 if (auth('customGuard')->attempt([
2 'email' => $email,
3 'password' => $password
4 ])) {
5 // Authentication passed.
6 }
When $guard is set to null, the AuthManager instance will internally set $guard equal to the
value of the auth.defaults.guard configuration key (by default this is web). The following
code samples would produce the same results:
3.3 policy($class)
The policy helper function can be used to retrieve a policy (a policy class can be any valid
PHP class) instance for a given $class. The $class can be either a string or an object instance.
If no policies for the given $class have been registered with the application an instance of
InvalidArgumentException will be thrown.
1 /home/vagrant/Code/Laravel/app
The app_path function can also be used to build paths relative to the application directory. This
is accomplished by supplying a string as the first and only argument. The following example will
make numerous calls to app_path. The resulting path will appear above the function call as a
comment.
Application and User Flow Helper Functions 70
1 // /home/vagrant/Code/Laravel/app/Commands
2 app_path('Commands');
3
4 // /home/vagrant/Code/Laravel/app/Console
5 app_path('Console');
6
7 // /home/vagrant/Code/Laravel/app/Console/
8 app_path('Console/');
It should be noted that the app_path function does not automatically add the trailing forward
slash (‘/’) character when constructing the final string. This can be observed in the last two
function calls in the example. If it is important that the path returned must always have a trailing
forward slash, the return value of the app_path can be passed into the str_finish function
like so:
1 // /home/vagrant/Code/Laravel/app/Console/
2 str_finish(app_path('Console'), '/');
3
4 // /home/vagrant/Code/Laravel/app/Console/
5 str_finish(app_path('Console/'), '/');
1 // /home/vagrant/Code/Laravel/
2 base_path();
3
4 // /home/vagrant/Code/Laravel/app
5 base_path('app');
6
7 // /home/vagrant/Code/Laravel/public
8 base_path('public');
Like the app_path function, the base_path function will not automatically add the trailing
slash to the final string.
Application and User Flow Helper Functions 71
1 // /home/vagrant/Code/Laravel/public/
2 str_finish(base_path('public'), '/');
1 // /home/vagrant/Code/Laravel/config/
2 config_path();
3
4 // /home/vagrant/Code/Laravel/config/database.php
5 config_path('database.php');
6
7 // /home/vagrant/Code/Laravel/config/app.php
8 config_path('app.php');
1 // /home/vagrant/Code/Laravel/database
2 database_path();
3
4 // /home/vagrant/Code/Laravel/migrations
5 database_path('migrations');
6
7 // /home/vagrant/Code/Laravel/seeds/
8 str_finish(database_path('seeds'), '/'):
1 // /home/vagrant/Code/Laravel/public
2 public_path();
3
4 // /home/vagrant/Code/Laravel/public/js
5 public_path('js');
The public_path does not automatically add the trailing slash / character to the final string.
public_path’s return value can be passed into the str_finish function to achieve the same
affect:
1 // /home/vagrant/Code/Laravel/public/js/
2 str_finish(public_path('js'), '/');
1 // /home/vagrant/Code/Laravel/storage
2 storage_path();
3
4 // /home/vagrant/Code/Laravel/storage/logs
5 storage_path('logs');
6
7 // /home/vagrant/Code/Laravel/storage/framework/sessions
8 storage_path('framework/sessions');
The storage_path does not automatically add the trailing slash / character to the final string.
storage_path’s return value can be passed into the str_finish function to achieve the same
affect:
1 // /home/vagrant/Code/Laravel/storage/logs/
2 str_finish(storage_path('logs'), '/');
If the $code supplied is 404, the abort function will return an instance of
Symfony\Component\HttpKernel\Exception\NotFoundHttpException using only the user
supplied $message.
The following example assumes that some $user object exists with the property admin. The
example will check to make sure that the admin property is true. If not, the code will abort with
a 401 (unauthorized access) error code.
1 if (!$user->admin) {
2 abort(401);
3 }
The abort_if helper function performs the same basic function as the abort helper function.
The only difference is that the abort_if defines one extra parameter: $boolean.
If the argument supplied for $boolean evaluates to true, the abort_if function will abort
execution of the application.
The following example assumes that some $user object exists with the property admin. The
example will check to make sure that the admin property is true. If not, the code will abort with
a 401 (unauthorized access) error code.
The abort_unless helper is the logical opposite of the abort_if helper function. Like abort
and abort_if, the abort_unless helper function has the potential to abort the executed of the
running application.
If the argument supplied for $boolean evaluates to false, the abort_unless function will
abort execution of the application.
The following example assumes that some $user object exists with the property admin. The
example will check to make sure that the admin property is true. If not, the code will abort with
a 401 (unauthorized access) error code.
1 abort_unless($user->admin, 401);
Application and User Flow Helper Functions 74
Which function you decide to use largely depends on preference and the semantics of the variable
names. For example, the abort_if function can make sense in the context of a subscription or
credit card that might be expired:
1 abort_if($subscription->expired, 401);
2 abort_if($creditCard->expired, 401);
The redirect helper function is a versatile helper function. The $to parameter is defined with
a default value of null. When $to is null, the redirect function by default will return an
instance of Illuminate\Routing\Redirector.
1 use Illuminate\Support\Facades\Redirect;
2
3 return redirect('/');
4 return redirect()->to('/');
5 return Redirect::to('/');
An argument supplied to $to should be the URL or URL segment that the user should be redirect
to. For example, if we had the following route defined for /:
1 Route::get('/', function() {
2 return "Hello, Universe!";
3 });
1 return redirect('/');
The Redirector will generate the full URL path before it does the redirect. The path / would
be converted to the following URL (the actual results will differ based on the path and domain
name):
1 http://laravel.artisan
The URL that would be internally generated and redirected to in the above example would be
(the actual URL will differ based on the path and domain name):
Application and User Flow Helper Functions 76
1 https://laravel.artisan
1 // The URL will not be rewritten by the `Redirector` when redirecting the use\
2 r.
3 return redirect('http://laravel.artisan/redirect/test?custom=url');
Appendix B: HTTP Status Codes contains a table of common HTTP status codes.
1 use Illuminate\Support\Facades\Redirect;
2
3 function postCreateSomeValue() {
4 // ... code here ...
5 return Redirect::back();
6 }
1 function postCreateSomeValue() {
2 return redirect()->back();
3 }
1 function postCreateSomeValue() {
2 // ... code here ...
3 return back();
4 }
Appendix B: HTTP Status Codes contains a table of common HTTP status codes.
1 // Redirect back with a "302: Found" status code and extra headers:
2
3 return back(302, ['Laravel' => 'Artisan']);
The following image shows the results of a request that contains the request headers. You can
see that the Laravel header is present:
Application and User Flow Helper Functions 79
The response helper function is a useful function that can be used to accomplish two
different tasks. If no arguments are supplied to the response function, an implementation of
Illuminate\Contracts\Routing\ResponseFactory will be returned (by default this is an
instance of Illuminate\Routing\ResponseFactory). The following example demonstrates
some of the different methods that are available when the response function is used in this
way:
1 return response()->view('welcome');
2 return response()->json(['Laravel' => 'Artisan']);
3 return response()->redirectTo('/');
The response function can also be used as a shortcut to the ResponseFactory::make method.
If any arguments are supplied to the response function, the function will internally make a call
to the ResponseFactory::make method passing all the arguments and returning the result (a
new instance of Illuminate\Http\Response). The following examples are equivalent in their
end results:
If the above examples had been returned from a controller or route the user would see the text
I am the response content! in their browser.
Appendix B: HTTP Status Codes contains a table of common HTTP status codes.
1 // Create a response with a "404: Not Found" status code and extra headers:
2 return response('Page not found.', 404, [
3 'Cache-Control' => 'public'
4 ]);
1 $requestInstance = request();
Since we have access to an instance of Request, we also have access to all of the instance
methods available on Request:
The following example demonstrates how to retrieve user input using instance methods. The
examples assume that name exists in the user input array.
The request helper function can also be used as a shortcut to the Request::input instance
method. To use the request function supply at least the $key to retrieve from user input (and
an optional $default value that will be returned if no user input exists for the given $key). The
following examples are identical in their end result:
Application and User Flow Helper Functions 81
Using the request helper function, we can access only a subset of the user’s input data:
Receiving a subset of data can also be accomplished using the shorthand syntax introduced in
Laravel 5.3. To take advantage of this shorthand syntax, simply supply an array as the only
argument to the request helper function:
When arguments are supplied to the view function an internal call to Factory::make will
take place and the created View instance will be returned as the result. The $view parameter
is the name of the view file, $data is the initial data that will be passed along to the view and
Application and User Flow Helper Functions 82
$mergeData is simply an additional array of data that can be merged with $data before being
supplied to the view. It is important to note that any array or object instance that implements
the Illuminate\Contracts\Support\Arrayable interface can be supplied as an argument
for the $data parameter.
For example, you can pass a Illuminate\Support\Collection instance as an argument for
$data but not for $mergeData. This will work:
1 $welcomeViewContents = view('welcome')->render();
After the above example has executed, the $welcomeViewContents variable would contain the
contents of the welcome.blade.php view file.
The examples below demonstrate different methods to achieve the same result:
1 use Illuminate\Facades\Input;
2
3 // Retrieve the old name using the Input facade:
4 $userName = Input::old('name');
5
6 // Retrieve the old name using the request()
7 // helper function:
8 $userName = request()->old('name');
1 /**
2 * The following code is simply creating a new event class
3 * to signal that a video was watched.
4 */
5
6 namespace App\Events;
7
8 use App\Video;
9 use App\Events\Event;
10 use Illuminate\Queue\SerializesModels;
11
12 class VideoWasWatched extends Event
13 {
14 use SerializesModels;
15
Application and User Flow Helper Functions 84
16 public $video;
17
18 /**
19 * Create a new event instance.
20 *
21 * @param Video $video
22 * @return void
23 */
24 public function __construct(Video $video)
25 {
26 $this->video = $video;
27 }
28 }
1 event('\App\Events\VideoWasWatched', $video);
Alternatively, an event can be fired by instantiating a new instance of the event class itself:
1 event(new VideoWasWatched($video));
In the above example, a $payloadwas not supplied. This is because the event instance itself will
become the payload. It is equivalent to the following:
3.21 dispatch($command)
The dispatch helper function can be used to push a new job onto the job queue (or dispatch the
job). The function resolves the configured Illuminate\Contracts\Bus\Dispatcher imple-
mentation from the Service Container and then calls the dispatch method in the Dispatcher
instance.
Assuming a variable $job exists that contains a valid queueable Job the following examples are
all equivalent:
Application and User Flow Helper Functions 85
1 use Illuminate\Contracts\Bus\Dispatcher;
2 use Illuminate\Support\Facades\Bus;
3
4 dispatch($job);
5 app(Dispatcher::class)->dispatch($job);
6 Bus::dispatch($job);
3.22 factory()
The factory function is used to create Eloquent models, generally used when testing an
application. The factory method can generally take one of four forms:
3.23 method_field($method)
The method_field helper function is a simple function that returns a new instance of
Illuminate\Support\HtmlString. The contents of the HtmlString instance is a hidden
HTML input field with the name _method and the a value of $method.
The following example highlights the results of the method_field function:
1 method_field('PUT');
2 method_field('POST');
3 method_field('GET');
4 method_field('PATCH');
5 method_field('DELETE');
The return value of the method_field function is an instance of HtmlString. The correspond-
ing HTML string value for each function call above would be:
Application and User Flow Helper Functions 86
The validator helper function is a versatile helper function. If no arguments are supplied
to the validator function (all arguments are optional), the function will return a Illumi-
nate\Contracts\Validation\Factory implementation instance (the default implementa-
tion will be an instance of Illuminate\Validation\Factory).
Using the the validator function without arguments and gaining access to the instance
methods is essentially the same as using the Illuminate\Support\Facades\Validator
facade. The following examples are equivalent; all the examples will make use of the request
helper function.
1 use Illuminate\Support\Facades\Validator;
2
3 // Using the Validator facade.
4 $validator = Validator::make(request()->all(), [
5 'title' => 'required|unique:posts|max:255',
6 'body' => 'required'
7 ]);
8
9 // Using the validator helper function.
10 $anotherValidator = validator()->make(request()->all(), [
11 'title' => 'required|unique:posts|max:255',
12 'body' => 'required'
13 ]);
The second example above can be shortened even further. You can supply the arguments for the
make instance method directly to the validator helper function. When you supply arguments
to the validator helper function it will call and return the value of the make instance method:
1 $validator = validator(request()->all, [
2 'title' => 'required|unique:posts|max:255',
3 'body' => 'required'
4 ]);
4. Configuration, Environment,
Security and Logging Helper
Functions
4.1 bcrypt($value, $options = [])
The bcrypt function will return a hashed representation of the given $value. The bcrypt
function also accepts an array of $options which can be used to affect how the hash is
computed. Each invocation of the bcrypt function should produce a different result, even if
the input remains the same.
The following example demonstrates how to call the bcrypt function:
1 $2y$10$6b8WZt.Ugwnjjb3JZQH51ecaG.VSjOOO2xCZ3t4s/MGGHU112hhD2
2 $2y$10$o/uJXcnrNDQraGgk1.VG9.LwssnANCyOEO8tCuiL5RlO33CpGo.Lq
3 $2y$10$7qWDkO43obCCN4hpNDt2Hut2xbg8xmKQHzZF/m4EdsGUHApXcKLyi
4 $2y$10$e4srCMoCOaIl9qd2wuk.8e2pBGTxaAu/bDi2CrNlRcNyXxvtYePIy
5 $2y$10$1MhsM.KaYpwoODuoBi7wmO6jUrMJ0xGaigL6/JMKAgb48CgyFz8tK
6 $2y$10$wTdq3XAG7/UKT0aO4u9lO.ZRcDiaF5p4fXMViticodID9oC/CTsJO
7 $2y$10$yHwchZ9HCKZjfnqqulQ7eu61noEwIVZBXKwSZ8.rvYyk9p0SXFNKG
8 $2y$10$5XvPyJE9EQ6DpOdYzM.NYeR4eDjAzntn2ogytDh1tNU4ebWrHaYvS
9 $2y$10$V1yb7D7rqqUL7BZkR2c3HOjYHvVB/lRg5cvrL/Hl/KYzrKrTV/tvC
10 $2y$10$6DAP/IjDTOH3iezOzx/CyuH37ZEDtc6.ADkDEfJUUn/msgUGe5A4S
87
Configuration, Environment, Security and Logging Helper Functions 88
bcrypt Options
Option Description
rounds Determines how many iterations the bcrypt function will internally use.
4.1.1.1 rounds
The rounds option is used to control how many iterations the underlying Blowfish implemen-
tation will use when generating the final hash. The rounds value can be any positive integer
between 4 and 31 (including both 4 and 31). If an integer outside the stated range is supplied
an ErrorException will be thrown. The rounds option is synonymous with the cost option
when using PHP’s password_hash or crypt functions. Increasing the rounds will also increase
the time required to compute the hash. The default value for this option is 10.
The number of iterations that will be used can be determined with the following equation:
iterations = 2rounds
Calling bcrypt with the rounds option set to 10 will use 21 0 or 1024 iterations.
4.2 encrypt($value)
The encrypt helper function can be used to encrypt a given $value. The function resolves
the configured Illuminate\Contracts\Encryption\Encrypter implementation from the
Service Container and then calls the encrypt method on the Encrypter instance.
The following examples are all equivalent:
Configuration, Environment, Security and Logging Helper Functions 89
1 use Illuminate\Support\Facades\Crypt;
2
3 // Encrypt using the Crypt facade:
4 Crypt::encrypt('Hello, Universe');
5
6 // Encrypt using the encrypt helper:
7 encrypt('Hello, Universe');
4.3 decrypt($value)
The decrypt helper function can be used to decrypt a given $value. The function resolves
the configured Illuminate\Contracts\Encryption\Encrypter implementation from the
Service Container and then calls the decrypt method on the Encrypter instance.
Assuming a variable $encryptedValue exists and contains a previously encrypted value the
following examples are all equivalent:
1 use Illuminate\Support\Facades\Crypt;
2
3 $encryptedValue = '...';
4
5 // Encrypt using the Crypt facade:
6 Crypt::decrypt($encryptedValue);
7
8 // Encrypt using the encrypt helper:
9 decrypt($encryptedValue);
4.4 csrf_field()
The csrf_field function can be used to generate a hidden HTML element containing the value
of the CSRF token. For example, the following HTML code can be greatly simplified using the
function:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>CSRF Token Form Sample</title>
5 </head>
6 <body>
7 <form>
8 <input type="hidden" name="_token"
9 value="<?php echo csrf_token(); ?>">
10
11 <!-- Other form inputs here -->
Configuration, Environment, Security and Logging Helper Functions 90
12 </form>
13 </body>
14 </html>
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>CSRF Token Form Sample</title>
5 </head>
6 <body>
7 <form>
8 <?php echo csrf_field(); ?>
9
10 <!-- Other form inputs here -->
11 </form>
12 </body>
13 </html>
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>CSRF Token Form Sample</title>
5 </head>
6 <body>
7 <form>
8 {!! csrf_field() !!}
9
10 <!-- Other form inputs here -->
11 </form>
12 </body>
13 </html>
4.5 csrf_token()
The csrf_token (cross-site request forgery token) function is a shortcut for retrieving the CSRF
token from the session storage.
CSRF Token
The CSRF token is stored in the session and is a random string 40 characters in length.
It is generated using the str_random(40) function call.
1 // WGuFrjvm7keNGqDhhW8jVnyC3W6zUv9w4mPexw9N
2 csrf_token();
The csrf_token function can also be used when generating HTML forms:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>CSRF Token Form Sample</title>
5 </head>
6 <body>
7 <form>
8 <input type="hidden" name="_token"
9 value="<?php echo csrf_token(); ?>">
10
11 <!-- Other form inputs here -->
12 </form>
13 </body>
14 </html>
It is possible that a session value does not exist. When this is the case, the internal session
mechanisms will return null. This can be overridden by supplying a value for the $default
parameter:
The cookie function is generally used to create a new instance of the \Symfony\Component\HttpFoundation
\Cookie class. If the supplied $name is null an implementation of \Illuminate\Contracts\Cookie
\Factory (which is an instance of \Illuminate\Cookie\CookieJar by default) is returned
instead. When not being used to return a CookieJar instance, the cookie function makes a call
to the make method on an instance of the CookieJar (which is resolved using the application
container) using all supplied parameters.
$name
This is the name of the new cookie. The names of cookies must be unique.
$value
The value to be stored in the cookie. Cookie values can be a numeric value or a string and
not more than 4KB in length.
$minutes
The number of minutes until the cookie expires. A “forever” cookie in Laravel is set to
expire in five years or roughly 2,628,000 minutes.
$path
This parameter determines which path on the web server the cookie will be available on.
For example, if the $path is set to /laravel/, the cookie will only be available within
the /laravel/ directory and all sub-directories. The cookies will also be available to any
routed actions that match the path. The default value of $path ultimately will be /, which
means the cookie is available on all paths.
$domain
The $domain parameter can be used to restrict where the cookie is available, just like the
$path parameter. Except, instead of working on web server paths it works on the domain
or sub-domain. Setting the $domain value to example.com makes the cookie available
on example.com, as well as sub-domains above it such as www.example.com. Setting a
cookie domain to ww3.www.example.com would make the cookie available to the ww3
sub-domain and higher, but not the www sub-domain.
To make a cookie available to all domains, prefix the domain with the . character.
So to make a cookie available on all sub-domains of example.com, set the domain to
.example.com.
If no domain is specified, the request host will be used as the $domain value, as specified
in RFC 2109 - HTTP State Management Mechanism¹.
$secure
The $secure parameter determines whether or not the cookie is only sent back to the
server over a HTTPS connection. If $secure is set to true, the cookie will only be sent
back over secure connections.
$httpOnly
The $httpOnly parameter determines if the cookie can only be accessed with the HTTP
protocol. If set to true, the cookie cannot be accessed by scripting languages such as
JavaScript.
The following examples highlight the basic usage of the cookie function to create various
cookies:
¹http://www.faqs.org/rfcs/rfc2109.html
Configuration, Environment, Security and Logging Helper Functions 94
In the above example all three key/value pairs will be stored in the configuration separately.
The following example highlights how the values are returned (by returning an instance of the
configuration repository). The value returned will appear above the function call as a comment:
Configuration, Environment, Security and Logging Helper Functions 95
1 // valueOne
2 config()->get('keyOne');
3
4 // valueTwo
5 config()->get('keyTwo');
6
7 // valueThree
8 config()->Get('keyThree');
1 // valueOne
2 config('keyOne');
3
4 // valueTwo
5 config('keyTwo');
6
7 // valueThree
8 config('keyThree');
9
10 // Not null
11 config('nonExistent', 'Not null');
1 APP_ENV=local
2 APP_DEBUG=true
3 APP_KEY=SomeRandomString
4
5 DB_HOST=localhost
6 DB_DATABASE=homestead
7 DB_USERNAME=homestead
8 DB_PASSWORD=secret
9
10 CACHE_DRIVER=file
11 SESSION_DRIVER=file
12
13 TEST_TRUE1=true
14 TEST_TRUE2=(true)
15
16 TEST_FALSE1=false
17 TEST_FALSE2=(false)
18
19 TEST_NULL1=null
20 TEST_NULL2=(null)
21
22 TEST_EMPTY1=empty
23 TEST_EMPTY2=(empty)
The returned value will appear above the function call as a comment (the actual values returned
will likely be different based on application specifics and environment configuration):
1 // local
2 env('APP_ENV');
3
4 // true
5 env('APP_DEBUG');
6
7 // A rather long default value
8 env('NonExistent', 'A rather long default value');
The env function will automatically convert boolean string representations and null represen-
tations into their corresponding PHP value. In the above example configuration file, the values
returned for TEST_TRUE1, TEST_TRUE2, TEST_FALSE1 and TEST_FALSE2 will automatically be
converted to a boolean type. The values returned for TEST_NULL1 and TEST_NULL2 will auto-
matically be converted to a null type. The values returned for TEST_EMPTY1 and TEST_EMPTY2
will actually be an empty string, with a length of 0.
Configuration, Environment, Security and Logging Helper Functions 97
The above code would produce results similar to the following (some lines have been indented
to improve readability and prevent wrapping):
1 ...
2 [2015-06-15 02:21:13] local.DEBUG: This is a log message without context
3 [2015-06-15 02:21:13] local.DEBUG: This is a log message
4 {"name":"John Doe","email":"you@homestead"}
5 [2015-06-15 02:21:13] local.DEBUG: This is another log message
6 [
7 "[object] (stdClass: {\"name\":\"John Doe\",\"email\":\"you@homestead\"})"
8 ]
9 ...
The above code would produce results similar to the following (some lines have been indented
to prevent wrapping and improve readability):
1 ...
2 [2015-06-15 02:14:43] local.INFO: This is a log message without context
3 [2015-06-15 02:14:43] local.INFO: This is a log message
4 {"name":"John Doe","email":"you@homestead"}
5 [2015-06-15 02:14:43] local.INFO: This is another log message
6 [
7 "[object] (stdClass: {\"name\":\"John Doe\",\"email\":\"you@homestead\"})"
8 ]
9 ...
5. URL Generation Helper Functions
5.1 action($name, $parameters = [], $absolute =
true)
The action helper function can be used to generate a URL to a controller action, which is
supplied as an argument to the $name parameter. If the controller action requires or accepts
parameters these can be supplied by utilizing the $parameters parameter.
The following examples will use the following example controller (stored in app/Http/Con-
trollers/ExampleController.php):
1 <?php
2
3 namespace App\Http\Controllers;
4
5 class ExampleController extends Controller {
6
7 public function sayHello($name) {
8 return "Hello, {$name}!";
9 }
10
11 }
as well as the following route definition (added to the web middleware group in app/Htp-
p/routes.php):
1 Route::get('sayHello/{name}', 'ExampleController@sayHello');
1 http://laravel.artisan/sayHello/Jim
The exact URL that is generated will depend on the current domain of the site.
Notice that when the action function was called, we did not need to include the root namespace
of the controller (App\Http\Controllers). Laravel will automatically add the namespace for
you. Any namespaces that are not part of the root namespace must be included (such as Auth),
however.
99
URL Generation Helper Functions 100
1 /sayHello/Jim
The application URI used to generate the final URI is what was used to issue the request, and
typically matches what appears in the browser’s address bar.
Assuming the application path is laravel.artisan the following asset paths can be generated
(the resulting URI appears above the function call as a comment):
1 // http://laravel.artisan/test
2 asset('test');
3
4 // http://laravel.artisan/js/application.min.js
5 asset('js/application.min.js');
6
7 // http://laravel.artisan/js/application.min.js
8 asset('http://laravel.artisan/js/application.mins.js');
5.3 secure_asset($path)
The secure_asset function will return a URI composed of the application’s URI and the given
$path. It internally makes a call to the asset helper function and always passes true as the
argument for the $secure parameter.
The following:
1 // https://laravel.artisan/js/application.min.js
2 secure_asset('js/application.min.js');
is equivalent to calling:
URL Generation Helper Functions 101
1 // https://laravel.artisan/js/application.min.js
2 asset('js/application.min.js', true);
1 // https://laravel.artisan/js/application.min.js
2 asset('https://laravel.artisan/js/application.min.js', false);
3
4 // http://laravel.artisan/js/application.min.js
5 secure_asset('http://laravel.artisan/js/application.min.js');
6
7 // http://laravel.developer/js/application.min.js
8 asset('http://laravel.developer/js/application.min.js');
The url helper function is a versatile function that can be used to generate a URL to a given path
or return an instance of the configured Illuminate\Contracts\Routing\UrlGenerator
implementation (by default this is an instance of Illuminate\Routing\UrlGenerator). The
url function can be used to generate arbitrary URLs.
Calling the url function without any arguments returns (by default) an instance of Illumi-
nate\Routing\UrlGenerator. Using the url function in this way is effectively the same as
using the Illuminate\Support\Facades\Url facade. All of the method/function calls in the
following example are equivalent:
1 use Illuminate\Support\Facades\Url;
2
3 Url::action('SomeController@someAction');
4 url()->action('SomeController@someAction');
5 action('SomeController@someAction');
If arguments are supplied to the url helper function, it will internally make a call to the
UrlGenerator instance method to, passing all the arguments along.
1 use Illuminate\Support\Facades\Url;
2
3 // Using the Url facade.
4 Url::to('arbitraryUrl');
5
6 // Using the url helper function.
7 url('arbitraryUrl');
1 http://laravel.artisan/arbitraryUrl
You can also include router parameters in the generated URL by utilizing the $parameters
parameter. The following function call:
1 url('arbitraryUrl', ['someParameter']);
1 http://laravel.artisan/arbitraryUrl/someParameter
1 https://laravel.artisan/arbitraryUrl
2 https://laravel.artisan/arbitraryUrl/someParameter
The secure_url helper function internally returns the value of a call to the url helper
function.
The following example demonstrates the usage of the secure_url helper function:
URL Generation Helper Functions 103
1 $url = secure_url('arbitraryUrl');
The resulting URL would look similar to the following output. The exact URL will change
depending on the $path and the domain name.
1 https://laravel.artisan/arbitraryUrl
To generate URLs with extra data, supply an argument for the $parameters array like so:
1 $url = secure_url('arbitraryUrl', [
2 'someParameter'
3 ])
1 https://laravel.artisan/arbitraryUrl/someParameter
The path to the file versioned using the default configured build directory can be determined
like this:
1 elixir('css/app.css');
1 /build/css/app-aa3c9d985b.css
Likewise, the path to the versioned file with the custom build directory can be determined by
supplying an argument for $buildDirectory:
1 elixir('css/app.css', 'build2');
1 /build2/css/app-64f4edce94.css
The route helper function can be used to generate URLs to a given named route. The route
function defines four parameters, but only three are used internally ($name, $parameters and
$absolute). It acts a shortcut to calling the Illuminate\Routing\UrlGenerator::route
instance method.
The $name is the name of the route to generate the URL for. Extra data can be supplied using
the $parameters array parameter that will be appended to the URL as a query string. The
$absolute parameter can be used to indicate if a fully qualified or relative URL will be returned
from the route helper function.
Assuming the following named route:
1 $url = route('profile');
The resulting URL would be look like this (the actual URL returned will change depending on
the route name and the domain name):
1 http://laravel.artisan/user/profile
Additional data can be added to the resulting query string by supplying an argument for
$parameters:
URL Generation Helper Functions 105
1 $url = route('profile', [
2 'custom' => 'data'
3 ]);
1 http://laravel.artisan/user/profile?custom=data
By default the route helper function generates fully qualified URLs. To change this behavior,
supply an argument with a truth value of false for the $absolute argument. The following
example demonstrates the differences in calling the route function with different $absolute
values:
The data_set helper function can be used to set the value of an item in an array or an object
property using dot notation. It accepts a reference to a $target array or object; the $key (array
key or object property name) of the data to set and the $value to be set. It also defines an
optional $overwrite parameter (which is set to true by default). If $overwrite is set to true,
any existing values for the $key will be replaced.
The following code example will show a very basic usage of the data_set function:
1 $testArray = [
2 'first_name' => 'Jane',
3 'last_name' => 'Doe',
4 'age' => 26
5 ];
6
7 data_set($testArray, 'first_name', 'Jill');
Because the $overwrite property is set to true by default the first_name item will now
contain the value Jill. If we modified the example to look like this:
106
Miscellaneous Helper Functions 107
1 $testArray = [
2 'first_name' => 'Jane',
3 'last_name' => 'Doe',
4 'age' => 26
5 ];
6
7 // Notice that `$overwrite` is set to `false`.
8 data_set($testArray, 'first_name', 'Jill', false);
The value of first_name would remain unchanged. Things get a little more interesting when
setting nested properties:
1 $testArray = [
2 'first_name' => 'Jane',
3 'last_name' => 'Doe',
4 'age' => 26
5 ];
6
7 data_set($testArray, 'occupation.name', 'Data Engineer');
8 data_set($testArray, 'occupation.status', 'Employed');
After the above example has executed the $testArray variable would contain a value similar
to the following output:
1 array:4 [
2 "first_name" => "Jane"
3 "last_name" => "Doe"
4 "age" => 26
5 "occupation" => array:2 [
6 "name" => "Data Engineer"
7 "status" => "Employed"
8 ]
9 ]
We can also use the asterisk (*) wild card character to set multiple nested properties at once:
Miscellaneous Helper Functions 108
1 $testArray = [
2 'first_name' => 'Jane',
3 'last_name' => 'Doe',
4 'age' => 26
5 ];
6
7 data_set($testArray, 'occupation.name', 'Data Engineer');
8 data_set($testArray, 'occupation.status', 'Employed');
9
10 data_set($testArray, 'occupation.*', null);
After the above example has executed the $testArray variable would contain a value similar
to the following output:
1 array:4 [
2 "first_name" => "Jane"
3 "last_name" => "Doe"
4 "age" => 26
5 "occupation" => array:2 [
6 "name" => null
7 "status" => null
8 ]
9 ]
After the above example has executed the $testObject variable would contain a value similar
to the following output:
Miscellaneous Helper Functions 109
1 {
2 "first_name": "Jane"
3 "last_name": "Doe"
4 "age": 26
5 }
1 // NULL
2 $departmentAddress = object_get($sampleObject, 'department.address');
1 // `No Address`
2 $departmentAddress = object_get($sampleObject, 'department.address',
3 'No Address');
6.6 trait_uses_recursive($trait)
The trait_uses_recursive function will return an array of all the traits that are used by a
class. It will also return any traits that the traits are using.
Given the traits and class:
1 <?php
2
3 trait TraitOne { }
4
5 trait TraitTwo {
6 use TraitOne;
7 }
8
9 trait TraitThree { }
10
11 trait TraitFour { }
12
13 class ExampleBaseClass {
14 use TraitFour;
15 }
16
17 class ExampleClass extends ExampleBaseClass {
18 use TraitTwo, TraitThree;
19 }
1 $traits = trait_uses_recursive('ExampleClass');
1 array(3) {
2 ["TraitTwo"] "TraitTwo"
3 ["TraitThree"] "TraitThree"
4 ["TraitOne"] "TraitOne"
5 }
It should be noted that TraitFour used by ExampleClass’s base class is not listed. The trait_-
uses_recursive only lists the traits in the immediate class.
The trait_uses_recursive function also works on class instances:
1 array(3) {
2 ["TraitTwo"] "TraitTwo"
3 ["TraitThree"] "TraitThree"
4 ["TraitOne"] "TraitOne"
5 }
6.7 value($value)
The value function will return the default value of the supplied $value. Although this sounds
redundant, if the supplied $value is an instance of the Closure class, the function will be
executed and the value will be returned. If the $value is not an instance of Closure, the value
is simply returned.
Using value with an instance of Closure:
1 $value = value(function()
2 {
3 return 42;
4 });
In the above example, $value would contain the integer 42, because it was returned from the
function.
The following example does not use an instance of Closure:
1 $value = value(42);
6.8 with($object)
The with function will simply return the supplied $object. This function can be used to invoke
methods on new class instances that are passed as function arguments:
Miscellaneous Helper Functions 112
1 <?php
2
3 class ExampleClass {
4
5 public function someMethod()
6 {
7 return 'some value';
8 }
9
10 // Other methods.
11
12 }
13
14 $value = with(new ExampleClass)->someMethod();
In the above example, $value would be contain the value some value.
Again, the value of $value would be some value. Both vanilla PHP method and the with
method are perfectly capable. However, the with function may help to improve readability and
clarify intent.
6.9 windows_os
The windows_os helper function can be used to determine if the host server is running a
Microsoft Windows® operating system. The function returns either true—if the server is
running Windows®—or false—if the server is not running Windows®.
Using this function you can write code like so:
Miscellaneous Helper Functions 113
1 <?php
2
3 if (windows_os()) {
4 // Windows� specific commands or instructions.
5 } else {
6 // Anything that is not Windows�.
7 }
1 <?php
2
3 if (strtolower(substr(PHP_OS, 0, 3)) === 'win') {
4 // Windows® specific commands or instructions.
5 } else {
6 // Anything that is not Windows®.
7 }
The tap helper function was added in Laravel version 5.3 and defined in the
src/Illuminate/Support/helpers.php file. This function can easily be integrated
into older Laravel code bases as it does not depend on any new fundamental framework
components.
The following example PHP classes will be used to demonstrate a trivial usage of the tap helper
function. The classes represent a crude “talker” system where one can add messages and retrieve
the final message back:
Stored in the app/Message.php file:
Miscellaneous Helper Functions 114
1 <?php
2
3 namespace App;
4
5 class Message
6 {
7
8 /**
9 * The actual message.
10 *
11 * @var string
12 */
13 protected $message = '';
14
15 /**
16 * Gets the original message.
17 *
18 * @return string
19 */
20 public function getOriginal()
21 {
22 return $this->message;
23 }
24
25 /**
26 * Changes the message.
27 *
28 * @param $message
29 * @return Message
30 */
31 public function change($message)
32 {
33 $this->message = $message;
34
35 return $this;
36 }
37
38 public function __toString()
39 {
40 return strtolower($this->message);
41 }
42
43 }
The Message class if fairly simple. It is simply a value object that wraps PHP’s native string data
type. It provides a few methods that can be used to retrieve the original value and change (mutate)
Miscellaneous Helper Functions 115
the internal value of the message. When the message is cast back to a string it is converted to its
lowercased variant. The important thing to notice is that the change method returns a reference
back to itself.
Stored in the app/Talker.php file:
1 <?php
2
3 namespace App;
4
5 class Talker
6 {
7
8 /**
9 * The actual parts of the message.
10 *
11 * @var array
12 */
13 protected $messageParts = [];
14
15 /**
16 * Adds a message part to the end of the message.
17 *
18 * @param $message
19 * @return Message
20 */
21 public function atEnd(Message $message)
22 {
23 array_push($this->messageParts, $message);
24 return $message;
25 }
26
27 /**
28 * Adds a message part to the start of the message.
29 *
30 * @param $message
31 * @return Message
32 */
33 public function atBeginning(Message $message)
34 {
35 array_unshift($this->messageParts, $message);
36 return $message;
37 }
38
39 /**
40 * Returns the string representation of the message.
41 *
Miscellaneous Helper Functions 116
42 * @return string
43 */
44 public function talk()
45 {
46 return ucfirst(implode(' ', $this->messageParts));
47 }
48
49 }
The Talker class is also very simple. It maintains an array of Message instances and allows you
to add them to either the beginning or ending of the array of messages. In addition, it allows you
to retrieve a string made up of all the individual messages with the first character upper cased.
Annoyingly the atEnd and atBeginning methods return the Message instance instead of the
Talker instance, which makes chaining rather difficult.
The following example will create a simple helper function to remove some of the steps of using
the Talker and Message APIs:
1 <?php
2
3 use App\Talker;
4 use App\Message;
5
6 /**
7 * Say something.
8 *
9 * string $message
10 * @return string
11 */
12 function saySomething($message) {
13 $talker = new Talker;
14 $talker->atBeginning(new Message)->change($message);
15 return $talker->talk();
16 }
1 <?php
2
3 echo saySomething('Hello World');
1 Hello world
It would be nice if we could return the value of the method chain from our function like so:
Miscellaneous Helper Functions 117
1 <?php
2
3 // ...
4
5 function saySomething($message) {
6 $talker = new Talker;
7 return $talker->atBeginning(new Message)->change($message)->talk();
8 }
9
10 // ...
However, that code would not work. This is because the atBeginning method on the Talker
class returns an instance of Message. The talk method does not exist on the Message class, and
if it did would probably not have the same behavior as the Talker instance method. We can use
the tap function to get around this quite easily:
1 <?php
2
3 // ...
4
5 function saySomething($message) {
6 $talker = new Talker;
7 return tap($talker, function($t) use ($message) {
8 $t->atBeginning(new Message)->change($message);
9 })->talk();
10 }
11
12 // ...
In the above example we are using the tap function to keep our method chain going. In addition
we are passing the $message parameter into the inner callback function so that we can use it.
The above example could actually be simplified further by using the with helper function to
return a new instance of Talker:
1 <?php
2
3 // ...
4
5 function saySomething($message) {
6 return tap(with(new Talker), function($t) use ($message) {
7 $t->atBeginning(new Message)->change($message);
8 })->talk();
9 }
10
11 // ...
The previous example is very contrived but does demonstrate a fairly basic use of the tap
helper function. More common use cases might be when passing around Eloquent models with
extensive method chaining.
The following example will make use of the Eloquent model factory builder to create a new
instance, modify an attribute, save the model and then return the created model instance:
1 <?php
2
3 use App\User;
4
5 $user = tap(factory(User::class)->make(), function($user) {
6 $user->setAttribute('name', 'No such a random name')
7 ->save();
8 });
After the above example has executed, the attributes of the $user model instance might look
similar to the following output:
Miscellaneous Helper Functions 119
1 array [
2 "name" => "No such a random name"
3 "email" => "Batz.Bridget@example.com"
4 "password" => "$2y$10$aXsXCEx3pkgmNcWpJFkAE.AMHoyk3o8XC6Kth3..."
5 "remember_token" => "nayR2BKwaQ"
6 "updated_at" => "2016-06-03 22:29:01"
7 "created_at" => "2016-06-03 22:29:01"
8 "id" => 7
9 ]
The actual attribute values will differ as they are randomly assigned a value from the model
factory. Because of the way we used the tap helper function we were able to modify the name
attribute elegantly, save the model and get the exact return value we wanted.
7. Overriding the Default Helper
Functions
The helper functions that are defined in the global namespace (those not defined in a support
class such as Illuminate\Support\Str) can be overridden. This is because each function is
created only if the function has not been previously declared elsewhere. To override the helper
functions, ensure that any custom functions are loaded before Laravel’s helper functions.
Although it is possible to override helper functions, and can be useful at times, it should be
done with caution. Most of the helper files are used extensively within the framework itself. If
the behavior, or arguments, to the function change it could have drastic side effects throughout
the entire code base. Even if a function is not used within the framework itself, Laravel specific
packages may make use of the function.
120
II Collections
“I was told I’d never make it to VP rank because I was too outspoken. Maybe so, but I think men
will always find an excuse for keeping women in their ‘place.’ So, let’s make that place the
executive suite and start more of our own companies.”
– Jean Bartik (1924 - 2011), Computer Programmer
After the above code executes, the variable $someValue would hold the value Some value.
It should be noted that even though array syntax works with collections, PHP’s array specific
functions will not work on an instance of a collection directly. Instead we have to retrieve the
underlying array from the collection.
The following code will throw an instance of ErrorException stating that array_values
expects the first parameter to be an object:
¹http://php.net/manual/en/class.arrayaccess.php
122
Basic Usage - Collections as Arrays 123
1 use Illuminate\Support\Collection;
2
3 $collection = new Collection;
4 $collection[] = 'First';
5 $collection[] = 'Second';
6 $collection[] = 'Third';
7
8 $values = array_values($collection);
Instead, the toArray method can be used to retrieve a representation of the underlying array:
1 use Illuminate\Support\Collection;
2
3 $collection = new Collection;
4 $collection[] = 'First';
5 $collection[] = 'Second';
6 $collection[] = 'Third';
7
8 $values = array_values($collection->toArray());
After the above code executes, $values would contain a value similar to the following:
1 array (size=3)
2 0 => string 'First' (length=5)
3 1 => string 'Second' (length=6)
4 2 => string 'Third' (length=5)
1 use Illuminate\Support\Collection;
2
3 $collection = new Collection;
4
5 $value = $collection['does_not_exist'];
Interacting with collections in this manner should be relatively uncommon in practice. The
Collection class provides many methods that aid developers in such situations. As an example,
the get method allows retrieval of data from the collection, with the option of returning a default
value:
Basic Usage - Collections as Arrays 124
1 use Illuminate\Support\Collection;
2
3 $collection = new Collection;
4
5 $value = $collection->get('does_not_exist', 'But I do');
After the above code is executed the $value variable would have the value But I do, and
the code will not throw an exception. The chapter Collections: The Public API contains more
information about the public methods available.
1 use Illuminate\Support\Collection;
2
3 // An array of test data.
4 $testData = [
5 'first' => 'This is the first',
6 'second' => 'This is the second',
7 'third' => 'This is third'
8 ];
9
10 // Create a new collection instance.
11 $collection = new Collection($testData);
Another way to create a Collection instance is to call the static make method on the
Collection class itself:
1 use Illuminate\Support\Collection;
2
3 // An array of test data.
4 $testData = [
5 'first' => 'This is the first',
6 'second' => 'This is the second',
7 'third' => 'This is third'
8 ];
9
10 // Create a new collection instance static 'make' method.
11 $collection = Collection::make($testData);
A convenient way to create a new Collection instance is to use the collect helper function.
The collect helper function internally returns a new instance of Collection passing in any
arguments to the class’s constructor. It’s most basic usage is:
Basic Usage - Collections as Arrays 125
9.1 all
The all method can be used to retrieve the underlying array that the collection is using to hold
its data. The following code demonstrates the usage of the all method:
1 use Illuminate\Support\Collection;
2
3 $items = [
4 'first' => 'I am first',
5 'second' => 'I am second'
6 ];
7
8 $collection = Collection::make($items);
9
10 $returnedItems = $collection->all();
After the above code has been executed, the $returnedItems variable would hold the following
value:
1 array (size=2)
2 'first' => string 'I am first' (length=10)
3 'second' => string 'I am second' (length=11)
We can also verify that the two arrays are indeed equal:
1 // true
2 $areEqual = $items === $returnedItems;
It should also be noted that the all method will preserve any nested collections:
¹http://php.net/manual/en/class.arrayaccess.php
²http://php.net/manual/en/class.iteratoraggregate.php
126
Collections: The Public API 127
1 use Illuminate\Support\Collection;
2
3 $items = [
4 'first' => 'I am first',
5 'second' => 'I am second',
6 'third' => new Collection([
7 'first' => 'I am nested'
8 ])
9 ];
10
11 $collection = Collection::make($items);
12
13 $returnedItems = $collection->all();
At this point, the $returnedItems variable would a value similar to the following:
1 array (size=3)
2 'first' => string 'I am first' (length=10)
3 'second' => string 'I am second' (length=11)
4 'third' =>
5 object(Illuminate\Support\Collection)[132]
6 protected 'items' =>
7 array (size=1)
8 'first' => string 'I am nested' (length=11)
To return an array, and have any nested collections converted to arrays, see the toArray method.
9.2 toArray
The toArray method is similar to the all method in that it will return the underlying array
that the collection instance is using. The difference, however, is that the toArray method
will convert any object instance it can into arrays (namely any object that implements the
Illuminate\Contracts\Support\Arrayable interface). Consider the following code:
1 use Illuminate\Support\Collection;
2
3 $items = [
4 'first' => 'I am first',
5 'second' => 'I am second',
6 'third' => new Collection([
7 'first' => 'I am nested'
8 ])
9 ];
10
Collections: The Public API 128
11 $collection = Collection::make($items);
12
13 $returnedItems = $collection->toArray();
After the above code has executed, the $returnedItems variable would contain a value similar
to the following output:
1 array (size = 3)
2 'first' => string 'I am first' (length=10)
3 'second' => string 'I am second' (length=11)
4 'third' =>
5 array (size=1)
6 'first' => string 'I am nested' (length=11)
1 $testArray = [
2 'one' => '1',
3 'two' => '2',
4 'three' => '3',
5 'four' => '4',
6 'five' => '5',
7 'six' => '6'
8 ];
9
10 $collection = new Collection($testArray);
11
12 $chunks = $collection->chunk(3);
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 object(Illuminate\Support\Collection)[133]
6 protected 'items' =>
7 array (size=3)
8 0 => string '1' (length=1)
9 1 => string '2' (length=1)
10 2 => string '3' (length=1)
11 1 =>
12 object(Illuminate\Support\Collection)[134]
13 protected 'items' =>
14 array (size=3)
15 0 => string '4' (length=1)
16 1 => string '5' (length=1)
17 2 => string '6' (length=1)
As you can see, the chunk method returned a new collection that contains two new collections,
each containing three elements. It should also be noted that the original array keys are missing
(there are no numerical word names). This can be changed by passing true as the second
argument:
Now the $chunks variable would have a value similar to the following:
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 object(Illuminate\Support\Collection)[133]
6 protected 'items' =>
7 array (size=3)
8 'one' => string '1' (length=1)
9 'two' => string '2' (length=1)
10 'three' => string '3' (length=1)
11 1 =>
12 object(Illuminate\Support\Collection)[134]
13 protected 'items' =>
14 array (size=3)
15 'four' => string '4' (length=1)
16 'five' => string '5' (length=1)
17 'six' => string '6' (length=1)
9.4 collapse
The collapse method combines all the first-level items of a collection into a new, single
collection. The returned value of the collapse method is an instance of the Collection class.
We will create a simple collection to work with like this:
1 use Illuminate\Support\Collection;
2
3 $first = [
4 0, 1, 2, 3, 4
5 ];
6
7 $second = [
8 5, 6, 7, 8 , 9
9 ];
10
11 $collection = new Collection([$first, $second]);
The $collection variable now has an internal structure similar to the following output:
1 object(Illuminate\Support\Collection)[132]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 array (size=5)
6 0 => int 0
7 1 => int 1
8 2 => int 2
9 3 => int 3
10 4 => int 4
11 1 =>
12 array (size=5)
13 0 => int 5
14 1 => int 6
15 2 => int 7
16 3 => int 8
17 4 => int 9
We can see that our collection contains two arrays. Using the collapse method, we can get a
Collection instance that combines the two arrays above:
1 $collapsed = $collection->collapse();
Now, the $collapsed variable would have a value similar to the following:
Collections: The Public API 131
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=10)
4 0 => int 0
5 1 => int 1
6 2 => int 2
7 3 => int 3
8 4 => int 4
9 5 => int 5
10 6 => int 6
11 7 => int 7
12 8 => int 8
13 9 => int 9
It should be noted that the collapse method does not recursively collapse inner arrays. The
following code sample will create another collection, this time with a nested array:
1 use Illuminate\Support\Collection;
2
3 $first = [
4 0, 1, 2, 3, 4
5 ];
6
7 $second = [
8 [5, 6, 7, 8 , 9]
9 ];
10
11 $collection = new Collection([$first, $second]);
If we collapsed the $collection, the result would be similar to the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=6)
4 0 => int 0
5 1 => int 1
6 2 => int 2
7 3 => int 3
8 4 => int 4
9 5 =>
10 array (size=5)
Collections: The Public API 132
11 0 => int 5
12 1 => int 6
13 2 => int 7
14 3 => int 8
15 4 => int 9
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'bear',
6 'whale',
7 'chicken',
8 'tardigrade'
9 ]);
10
11 // true
12 $collection->contains('bear');
13
14 // true
15 $collection->contains('tardigrade');
16
17 // false
18 $collection->contains('dog');
The following demonstrates using the contains method to check if a given key/value pair exists
in a collection that contains arrays as items:
Collections: The Public API 133
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['big' => 'bear'],
6 ['bigger' => 'whale'],
7 ['small' => 'chicken'],
8 ['smaller' => 'tardigrade']
9 ]);
10
11 // true
12 $collection->contains('big', 'bear');
13
14 // true
15 $collection->contains('smaller', 'tardigrade');
16
17 // false
18 $collection->contains('smaller', 'paramecium');
The following example shows how the contains method can be used on collections of objects,
using a hypothetical User class:
1 use Illuminate\Support\Collection;
2
3 class User
4 {
5
6 /**
7 * A hypothetical user's first name.
8 *
9 * @var string
10 */
11 public $firstName = '';
12
13 /**
14 * A hypothetical user's favorite number.
15 *
16 * @var integer
17 */
18 public $favoriteNumber = 0;
19
20 public function __construct($firstName, $favoriteNumber)
21 {
22 $this->firstName = $firstName;
23 $this->favoriteNumber = $favoriteNumber;
24 }
Collections: The Public API 134
25
26 }
27
28 // Create a new collection instance.
29 $collection = new Collection([
30 new User('Jane', 7),
31 new User('Sarah', 9),
32 new User('Ben', 2)
33 ]);
34
35 // true
36 $collection->contains('firstName', 'Jane');
37
38 // false
39 $collection->contains('firstName', 'Josh');
40
41 // false
42 $collection->contains('lastName', 'Jane');
43
44 // true
45 $collection->contains('favoriteNumber', 2);
A function can also be supplied as the only argument to the contains method. The following
example demonstrates how to determine if there are any user’s that have favorite numbers
greater than 7:
1 // true
2 $collection->contains(function($key, $value) {
3 return $value->favoriteNumber > 7;
4 });
It should be noted that in the above example that the $value will be an instance of the User
class. Additionally, truth tests can be as complex as required. The following will determine if
there are any favorite numbers between 7 and 9, including 7 and 9:
1 // true
2 $collection->contains(function($key, $value) {
3 return ($value->favoriteNumber >= 7 && $value->favoriteNumber <= 9);
4 });
1 use Illuminate\Support\Collection;
2
3 $collection = new Collection([
4 'first', 'second', 'third'
5 ]);
6
7 // true
8 $collection->contains('third');
9
10 // true
11 $collection->contains('third', null);
Even though the two examples return true, the second example is functionally not correct.
When explicitly passing null as the second argument, the contains method will always return
true:
1 // true
2 $collection->contains('fourth', null);
The above example returns true even though fourth is not in the collection.
9.6 count
The count method is a straightforward method and simply returns the total number of items in
the collection. The count method returns an integer.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // 3
9 $collection->count();
9.7 diff($items)
The diff method is used to determine which items in the collection are not present in
the supplied $items collection. $items can be be either an array, or another instance of
Collection. The diff method returns a new instance of Collection.
1 use Illuminate\Support\Collection;
2
3 // Create the first collection instance.
4 $firstCollection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // Create the second collection instance.
9 $secondCollection = new Collection([
10 'third', 'fourth', 'fifth'
11 ]);
12
13 // ['first', 'second']
14 $firstCollection->diff(['third', 'fourth', 'fifth']);
15
16 // ['first', 'second']
17 $firstCollection->diff($secondCollection);
18
19 // ['fourth', 'fifth']
20 $secondCollection->diff($firstCollection);
9.8 diffKeys($items)
The diffKeys method is similar to the diff method. It is used to determine which items whose
keys in the collection are not present in the supplied $items collection’s keys. $items can be
either an array, or another instead of Collection.
The following example shows the basic usage of the diffKeys method:
After the code has executed the $differences variable would contain a value similar to the
following:
1 Collection {
2 #items: array:1 [
3 "price" => 799.99
4 ]
5 }
The result only contains the item price, because that is the only item in the $firstCollection
that was not present in the $secondCollection.
If we had reversed the order of the collections to the following:
Collections: The Public API 137
1 Collection {
2 #items: array:1 [
3 "description" => "Much shinier and bigger!"
4 ]
5 }
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // firstsecondthird
9 $collection->each(function($item, $key) {
10 echo $item;
11 });
12
13 // Break out of the loop early. Will display
14 // 'first' only.
15 $collection->each(function($item, $key) {
16 if ($item == 'second') {
17 return false;
18 }
19
20 echo $item;
21 });
Collections: The Public API 138
The each method does not explicitly allow the modification of a collection’s items, and simply
returns a reference to the original collection. However, of the way PHP treats objects as
references, it is possible to modify the properties of objects within a collection:
1 use Illuminate\Support\Collection;
2
3 class User
4 {
5
6 /**
7 * A hypothetical user's first name.
8 *
9 * @var string
10 */
11 public $firstName = '';
12
13 /**
14 * A hypothetical user's favorite number.
15 *
16 * @var integer
17 */
18 public $favoriteNumber = 0;
19
20 public function __construct($firstName, $favoriteNumber)
21 {
22 $this->firstName = $firstName;
23 $this->favoriteNumber = $favoriteNumber;
24 }
25
26 }
27
28 // Create a new collection instance.
29 $collection = new Collection([
30 new User('Jane', 7),
31 new User('Sarah', 9),
32 new User('Ben', 2)
33 ]);
34
35 // Change everyone's favorite number to 3.
36 $collection->each(function($item, $key) {
37 $item->favoriteNumber = 3;
38 });
After the above call to each, the $collection variable would contain a value similar to the
following output:
Collections: The Public API 139
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=3)
4 0 =>
5 object(User)[134]
6 public 'firstName' => string 'Jane' (length=4)
7 public 'favoriteNumber' => int 3
8 1 =>
9 object(User)[135]
10 public 'firstName' => string 'Sarah' (length=5)
11 public 'favoriteNumber' => int 3
12 2 =>
13 object(User)[136]
14 public 'firstName' => string 'Ben' (length=3)
15 public 'favoriteNumber' => int 3
It should also be noted that the each method affects the original Collection instance and does
not return a modified copy of the original Collection instance.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', '0', null
6 ]);
7
8 // ['first', 'second']
9 $filtered = $collection->filter();
10
11 // ['0', null]
12 $filtered = $collection->filter(function($item) {
13 return $item == false;
14 });
15
16 // ['second']
17 $filtered = $collection->item(function($item) {
Collections: The Public API 140
The first method is used to get the first item in a collection, or to get the first item in a
collection that matches a set of criteria. A $callback can be supplied to return the first item in
the collection that matches a given truth test. Additionally, an optional $default argument can
be passed that will be returned if there are no items that match the given criteria.
The following example shows how to get the first item in a collection:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // first
9 $value = $collection->first();
If the collection is empty (having no items), the first method will return null:
1 use Illuminate\Support\Collection;
2
3 // Create an empty collection.
4 $collection = new Collection([]);
5
6 // null
7 $value = $collection->first();
The $default parameter cannot be used when trying to get the first item in an empty collection:
1 use Illuminate\Support\Collection;
2
3 // Create an empty collection.
4 $collection = new Collection([]);
5
6 // null
7 $value = $collection->first(null, 'default-value');
A $callback argument can be passed to provide a truth test when evaluating which item should
be returned first:
Collections: The Public API 141
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // second
9 $value = $collection->first(function($key, $value) {
10 return strlen($value) > 5;
11 });
The $default parameter can be used in conjunction with the $callback parameter to return
a default value when there are no items in a collection that pass the given truth test:
1 use Illuminate\Support\Collection;
2
3 // null
4 $value = $collection->first(function($key, $value) {
5 return strlen($value) > 10;
6 });
7
8 // default-value
9 $value = $collection->first(function($key, $value) {
10 return strlen($value) > 10;
11 }, 'default-value');
9.12 flatten
The flatten method will return a new Collection instance representing a flattened version
of the original collection’s items. The flatten method internally makes use of the Illu-
minate\Support\Arr::flatten($array) helper method. The flatten method will not
preserve any keys from the original collection.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first',
6 'second' => [
7 'nested',
8 'array',
9 [
10 'deeply',
Collections: The Public API 142
11 'nested'
12 ]
13 ],
14 'third' => 'some-value'
15 ]);
16
17 // Flatten the original collection.
18 $flattenedCollection = $collection->flatten();
The $flattenedCollection variable will hold an instance of the Collection class and will
have a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=6)
4 0 => string 'first' (length=5)
5 1 => string 'nested' (length=6)
6 2 => string 'array' (length=5)
7 3 => string 'deeply' (length=6)
8 4 => string 'nested' (length=6)
9 5 => string 'some-value' (length=10)
It is obvious in the above output that the flatten method does not preserve any of the original
keys, and will even flatten deeply nested arrays.
9.13 flip
The flip method will return a new Collection instance where are the all the collection item’s
keys have been exchanged with their corresponding values.
The following code example demonstrates the effects of the flip method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second',
7 'third' => 'I am third'
8 ]);
9
10 // Flip the original collection.
11 $flippedCollection = $collection->flip();
The $flippedCollection variable will now contain a new instance of the Collection class
with a structure similar to the following output:
Collections: The Public API 143
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 'I am first' => string 'first' (length=5)
5 'I am second' => string 'second' (length=6)
6 'I am third' => string 'third' (length=5)
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 0,1,2,3,4,5,6,7,8,9,10
6 ]);
7
8 // Get the "fifth" page of the collection
9 // assuming there are two items per page.
10 $fifthPage = $collection->forPage(5, 2);
The $fifthPage variable will now contain an instance of the Collection class and will have
a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => int 8
5 1 => int 9
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 0,1,2,3,4,5,6,7,8,9,10
6 ]);
7
8 // Chunk the collection into smaller collections,
9 // with each page containing two items.
10 $pages = $collection->chunk(2);
The $pages variable is also an instance of Collection and contains other collections repre-
senting our pages, each with two items. The get method can be used to retrieve the fifth page
(4 is passed because the keys of the collection are zero-based):
Like before, the $fifthPage will be an instance of Collection and will have a value similar
to the following output:
1 object(Illuminate\Support\Collection)[138]
2 protected 'items' =>
3 array (size=2)
4 0 => int 8
5 1 => int 9
9.15 forget($key)
The forget method removes an item from the collection based on given $key. The forget
method returns a reference to the original collection, meaning it modifies the collection instance
it was called on.
The following code example should how the forget method can be used to remove an item
from a collection:
Collections: The Public API 145
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second'
7 ]);
8
9 // Remove the 'first' item from the collection.
10 $collection->forget('first');
The $collection will now contain only the second item, and will have a structure similar to
the following:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=1)
4 'second' => string 'I am second' (length=11)
Numerical keys can also be passed to the forget method to remove items from a collection:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection.
4 $collection = new Collection([
5 'I am first',
6 'I am second'
7 ]);
8
9 // Remove the 'first' item from the collection
10 // using a numerical key.
11 $collection->forget(0);
Like before, the $collection will have a structure similar to the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=1)
4 1 => string 'I am second' (length=11)
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second'
7 ]);
8
9 // I am second
10 $second = $collection->get('second');
By default, the get method will return null if a $key does not exist within the collection.
However, a different value can be supplied, as well as a callback:
1 // null
2 $value = $collection->get('third');
3
4 // default
5 $value = $collection->get('third', 'default');
6
7 // default
8 $value = $collection->get('third', function() {
9 return 'default';
10 });
The get method can also retrieve items based on numeric keys:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first',
6 'second',
7 'third'
8 ]);
9
10 // first
11 $value = $collection->get(0);
collection should be grouped by. By default, the groupBy method does not preserve the keys of
the collection when grouping, but that can be changed by passing true to the $preserveKeys
parameter. The groupBy returns a new instance of the Collection class.
The following collection will be used throughout this section when demonstrating the groupBy
method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 [
6 'genus' => 'Canis',
7 'species' => 'C. lupus',
8 'subspecies' => 'C. l. albus',
9 'name' => 'tundra wolf'
10 ],
11 [
12 'genus' => 'Canis',
13 'species' => 'C. lupus',
14 'subspecies' => 'C. l. arctos',
15 'name' => 'arctic wolf'
16 ],
17 [
18 'genus' => 'Cucumis',
19 'species' => 'C. sativus',
20 'subspecies' => null,
21 'name' => 'cucumber'
22 ]
23 ]);
1 $genera = $collection->groupBy('genus');
The $genera variable will now be an instance of Collection, and will contain numerous items,
each an instance of Collection. The above $genera variable will now have a value similar to
the following output:
Collections: The Public API 148
1 object(Illuminate\Support\Collection)[137]
2 protected 'items' =>
3 array (size=2)
4 'Canis' =>
5 object(Illuminate\Support\Collection)[135]
6 protected 'items' =>
7 array (size=2)
8 0 =>
9 array (size=4)
10 'genus' => string 'Canis' (length=5)
11 'species' => string 'C. lupus' (length=8)
12 'subspecies' => string 'C. l. albus' (length=11)
13 'name' => string 'tundra wolf' (length=11)
14 1 =>
15 array (size=4)
16 'genus' => string 'Canis' (length=5)
17 'species' => string 'C. lupus' (length=8)
18 'subspecies' => string 'C. l. arctos' (length=12)
19 'name' => string 'arctic wolf' (length=11)
20 'Cucumis' =>
21 object(Illuminate\Support\Collection)[136]
22 protected 'items' =>
23 array (size=1)
24 0 =>
25 array (size=4)
26 'genus' => string 'Cucumis' (length=7)
27 'species' => string 'C. sativus' (length=10)
28 'subspecies' => null
29 'name' => string 'cucumber' (length=8)
The original collection was split into two new collections: Cucumis and Canis. Each item that
was grouped into the Canis collection can be retrieve like so:
1 $canisGenus = $genera->get('Canis'):
The $canisGenus variable would now contain a value similar to the following output:
Collections: The Public API 149
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 array (size=4)
6 'genus' => string 'Canis' (length=5)
7 'species' => string 'C. lupus' (length=8)
8 'subspecies' => string 'C. l. albus' (length=11)
9 'name' => string 'tundra wolf' (length=11)
10 1 =>
11 array (size=4)
12 'genus' => string 'Canis' (length=5)
13 'species' => string 'C. lupus' (length=8)
14 'subspecies' => string 'C. l. arctos' (length=12)
15 'name' => string 'arctic wolf' (length=11)
A callback can also be supplied for the $groupBy parameter. The callback should accept an $item
and a $key argument, and should also return the criteria that the collection should be grouped
by. The following code example will group the original collection based on the length of each
items name:
1 object(Illuminate\Support\Collection)[137]
2 protected 'items' =>
3 array (size=2)
4 11 =>
5 object(Illuminate\Support\Collection)[135]
6 protected 'items' =>
7 array (size=2)
8 0 =>
9 array (size=4)
10 'genus' => string 'Canis' (length=5)
11 'species' => string 'C. lupus' (length=8)
12 'subspecies' => string 'C. l. albus' (length=11)
13 'name' => string 'tundra wolf' (length=11)
14 1 =>
15 array (size=4)
16 'genus' => string 'Canis' (length=5)
17 'species' => string 'C. lupus' (length=8)
Collections: The Public API 150
1 use Illuminate\Support\Collection;
2
3
4 // Create a new collection instance.
5 $collection = new Collection([
6 'first' => ['name' => 'Dave', 'age' => 30],
7 'second' => ['name' => 'Jim', 'age' => 30],
8 'third' => ['name' => 'Sarah', 'age' => 27]
9 ]);
10
11 $grouped = $collection->groupBy('age');
The $grouped variable would now have a value similar to the following output:
1 object(Illuminate\Support\Collection)[137]
2 protected 'items' =>
3 array (size=2)
4 30 =>
5 object(Illuminate\Support\Collection)[135]
6 protected 'items' =>
7 array (size=2)
8 0 => <== Notice that the keys were NOT preserved.
9 array (size=2)
10 'name' => string 'Dave' (length=4)
11 'age' => int 30
12 1 => <== Notice that the keys were NOT preserved.
Collections: The Public API 151
13 array (size=2)
14 'name' => string 'Jim' (length=3)
15 'age' => int 30
16 27 =>
17 object(Illuminate\Support\Collection)[136]
18 protected 'items' =>
19 array (size=1)
20 0 => <== Notice that the keys were NOT preserved.
21 array (size=2)
22 'name' => string 'Sarah' (length=5)
23 'age' => int 27
The groupBy method can be instructed to preserve keys by passing true for the $preserveKeys
parameter:
The $grouped variable would now contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[137]
2 protected 'items' =>
3 array (size=2)
4 30 =>
5 object(Illuminate\Support\Collection)[135]
6 protected 'items' =>
7 array (size=2)
8 'first' => <== Notice that keys WERE preserved.
9 array (size=2)
10 'name' => string 'Dave' (length=4)
11 'age' => int 30
12 'second' => <== Notice that keys WERE preserved.
13 array (size=2)
14 'name' => string 'Jim' (length=3)
15 'age' => int 30
16 27 =>
17 object(Illuminate\Support\Collection)[136]
18 protected 'items' =>
19 array (size=1)
20 'third' => <== Notice that keys WERE preserved.
21 array (size=2)
22 'name' => string 'Sarah' (length=5)
23 'age' => int 27
Collections: The Public API 152
9.18 has($key)
The has method is used to determine if a item exists in the collection based on a given $key.
The has method returns true if the item exists and false if it does not.
The following example demonstrates the usage of the has method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second'
7 ]);
8
9 // true
10 $collection->has('first');
11
12 // true
13 $collection->has('second');
14
15 // false
16 $collection->has('third');
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // first-second-third
9 $imploded = $collection->implode('-');
³http://php.net/manual/en/function.implode.php
Collections: The Public API 153
When using the implode method on collections that contain arrays or objects, two arguments
are required: the $value that should be combined and the $glue that should combine each
value. The following code example shows how to use the implode method in this context:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['name' => 'Laravel', 'version' => '5.1'],
6 ['name' => 'Lumen', 'version' => '5.0']
7 ]);
8
9 // Laravel, Lumen
10 $imploded = $collection->implode('name', ', ');
The above code sample shows how to use the implode method with collections containing
arrays. The following code sample will use Eloquent’s model factory to create instances of the
User class with some fake data. The final result of the code sample will be to create a message
that can be displayed to end users of a micro-blogging platform that allows users to follow each
other:
The exact value of $notification will change each time the above code is executed because
random data is being populated using the Faker⁴ package. However, the above script produces
results similar to the following:
1 Kathryn Fisher, Pink Spencer and Ben Pagac have recently followed you.
2 Maureen Anderson, Samson Ondricka DVM and Otis Metz have recently followed yo\
3 u.
4 Herman Ziemann, Shemar Tremblay and Presley Barrows have recently followed yo\
5 u.
9.20 intersect($items)
The intersect removes any values that are not in the provided $items array. The intersect
method returns a new instance of Collection. The intersect method preserves any keys
from the original collection.
The following code example highlights the usage of the intersect method:
⁴https://github.com/fzaninotto/Faker
Collections: The Public API 154
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // An empty collection will be returned.
9 $intersected = $collection->intersect(['fourth']);
10
11 // A collection only containing the 'third' value will
12 // be returned.
13 $intersected = $collection->intersect(['fourth', 'third']);
9.21 isEmpty
The isEmpty can be used to determine if the collection has items or not. If the collection has no
items, true will be returned, otherwise false will be returned.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection;
5
6 // true
7 $empty = $collection->isEmpty();
8
9 // Add an item to the collection.
10 $collection[] = 'First item';
11
12 // false
13 $empty = $collection->isEmpty();
9.22 jsonSerialize
The jsonSeralize method internally returns the value of the toArray method. This method
exists to implement PHP’s JsonSerializable⁵ interface, which allows developers to customize
how a class is represented when using the json_encode function.
⁵http://php.net/manual/en/class.jsonserializable.php
Collections: The Public API 155
1 use Illuminate\Support\Collection;
2
3 // Create a new collection.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // Get the value that should be encoded with
9 // json_encode.
10 $value = $collection->jsonSerialize();
The $value variable would contain a value similar to the following output:
1 array (size=3)
2 0 => string 'first' (length=5)
3 1 => string 'second' (length=6)
4 2 => string 'third' (length=5)
9.23 keys
The keys method is used to retrieve the keys of all items in the collection. The keys method
returns a new Collection instance.
The following code example demonstrates the usage of the keys method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 $keys = $collection->keys();
After the above code executes, the $keys variable would contain a value similar to the following
output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => int 0
5 1 => int 1
6 2 => int 2
The following shows a sample, with output, of a collection containing items represented by an
associative array:
Collections: The Public API 156
1 use Illuminate\Support\Collection;
2
3
4 // Create a new collection.
5 $collection = new Collection([
6 'first' => 'I am first',
7 'second' => 'I am second',
8 'third' => 'I am third'
9 ]);
10
11 $keys = $collection->keys();
The $keys variable would now contains a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'first' (length=5)
5 1 => string 'second' (length=6)
6 2 => string 'third' (length=5)
The last method is the logical opposite of the first method, and is used to get the last item in a
collection, or to get the last item in a collection that matches a certain criteria. A $callback can
be supplied to return the last item in the collection that matches a given truth test. Additionally,
an optional $default argument can be passed that will be returned if there are no items that
match the given criteria.
The following example shows how to get the last item in a collection:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // third
9 $value = $collection->last();
If the collection is empty (having no items), the last method will return null:
Collections: The Public API 157
1 use Illuminate\Support\Collection;
2
3 // Create an empty collection.
4 $collection = new Collection([]);
5
6 // null
7 $value = $collection->last();
The $default parameter cannot be used when trying to get the last item in an empty collection:
1 use Illuminate\Support\Collection;
2
3 // Create an empty collection.
4 $collection = new Collection([]);
5
6 // null
7 $value = $collection->last(null, 'default-value');
A $callback argument can be passed to provide a truth test when evaluating which item should
be returned last:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // second
9 $value = $collection->last(function($key, $value) {
10 return strlen($value) > 5;
11 });
The $default parameter can be used in conjunction with the $callback parameter to return
a default value when there are no items in a collection that pass the given truth test:
Collections: The Public API 158
1 use Illuminate\Support\Collection;
2
3 // null
4 $value = $collection->last(function($key, $value) {
5 return strlen($value) > 10;
6 });
7
8 // default-value
9 $value = $collection->last(function($key, $value) {
10 return strlen($value) > 10;
11 }, 'default-value');
1 use Illuminate\Support\Collection;
2
3 // Create a new collection.
4 $collection = new Collection([
5 ['name' => 'Laravel', 'version' => '5.1'],
6 ['name' => 'Lumen', 'version' => '5.0']
7 ]);
8
9 // Get a list of product names.
10 $productNames = $collection->lists('name');
11
12 // Get a list of product versions.
13 $productVersions = $collection->lists('version');
After the above code has been executed, the $productNames variable would contain a value
similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'Laravel' (length=7)
5 1 => string 'Lumen' (length=5)
and the $productVersions variable would contains a value similar to the following output:
Collections: The Public API 159
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string '5.1' (length=3)
5 1 => string '5.0' (length=3)
The following code example will return a new collection with the version as the value and the
product name as the key of the resulting collection:
The $products variable would then contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 'Laravel' => string '5.1' (length=3)
5 'Lumen' => string '5.0' (length=3)
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // Create a new collection where all the strings
9 // in the original collection have had their case
10 // changed to upper-case.
11 $newCollection = $collection->map(function($item, $key) {
12 return strtoupper($item);
13 });
The $newCollection variable will be an instance of the Collection class and contain a value
similar to following output:
Collections: The Public API 160
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'FIRST' (length=5)
5 1 => string 'SECOND' (length=6)
6 2 => string 'THIRD' (length=5)
1 <?php
2
3 use Illuminate\Support\Collection;
4
5 // Create a new collection instance.
6 $collection = new Collection([
7 'first', 'second', 'third'
8 ]);
9
10 // Create a new collection where all the strings
11 // in the original collection have had their case
12 // changed to upper-case.
13 $newCollection = $collection->map(function($item, $key) {
14 return strtoupper($item);
15 })->collapse();
16
17
18 // Using the flatMap method
19 $newCollection = $collection->flatMap(function($item, $key) {
20 return strtoupper($item);
21 });
The following code example highlights the usage of max without specifying a $key:
⁶http://php.net/manual/en/function.max.php
Collections: The Public API 161
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 0, 1, 2, 3, 4, 5
6 ]);
7
8 // 5
9 $max = $collection->max();
After the above code has executed the $max variable would contain the value 5. The following
code example shows how to use the max function when specifying a $key:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['name' => 'Laravel', 'version' => '5.1'],
6 ['name' => 'Lumen', 'version' => '5.0']
7 ]);
8
9 // 5.1
10 $max = $collection->max('version');
11
12 // Lumen
13 $maxName = $collection->max('name');
After the above code has executed the $max variable would contain the value 5.1 and the
$maxName variable would contain the value Lumen.
9.28 merge($items)
The merge methods merges the given $items with the items in the collection. The merge method
will replace any item in the original collection’s items if a string key with the same value exists in
the supplied $items. If the $items keys are numeric, the new $items will be added to the end
of the new collection’s items. The merge method can accept either an array or a Collection
instance. The merge method returns a new instance of Collection and does not modify the
original collection instance.
Collections: The Public API 162
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // Merge an array with the existing collection.
9 $newCollection = $collection->merge(['fourth']);
After the above code has executed, the $newCollection variable will be an instance of
Collection and contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=4)
4 0 => string 'first' (length=5)
5 1 => string 'second' (length=6)
6 2 => string 'third' (length=5)
7 3 => string 'fourth' (length=6)
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 0, 1, 2, 3, 4, 5
6 ]);
7
8 // 0
9 $min = $collection->min();
After the above code has executed the $min variable would contain the value 0. The following
code example shows how to use the min function when specifying a $key:
⁷http://php.net/manual/en/function.min.php
Collections: The Public API 163
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['name' => 'Laravel', 'version' => '5.1'],
6 ['name' => 'Lumen', 'version' => '5.0']
7 ]);
8
9 // 5.0
10 $min = $collection->min('version');
11
12 // Laravel
13 $minName = $collection->min('name');
After the above code has executed the $min variable would contain the value 5.0 and the
$minName variable would contain the value Laravel.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection.
4 $collection = new Collection([
5 ['name' => 'Laravel', 'version' => '5.1'],
6 ['name' => 'Lumen', 'version' => '5.0']
7 ]);
8
9 // Get a list of product names.
10 $productNames = $collection->pluck('name');
11
12 // Get a list of product versions.
13 $productVersions = $collection->pluck('version');
After the above code has been executed, the $productNames variable would contain a value
similar to the following output:
Collections: The Public API 164
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'Laravel' (length=7)
5 1 => string 'Lumen' (length=5)
and the $productVersions variable would contains a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string '5.1' (length=3)
5 1 => string '5.0' (length=3)
The following code example will return a new collection with the version as the value and the
product name as the key of the resulting collection:
The $products variable would then contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 'Laravel' => string '5.1' (length=3)
5 'Lumen' => string '5.0' (length=3)
9.31 pop
The pop method is used to retrieve the last item from the collection while also removing it from
the collection. If there are no items in the collection, the pop method will return null.
The following sample demonstrates the use of the pop method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // third
9 $third = $collection->pop();
The pop method alters the original collection, so the $collection variable would now contain
a value similar to the following output:
Collections: The Public API 165
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'first' (length=5)
5 1 => string 'second' (length=6)
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'XS', 'S', 'M', 'L', 'XL'
6 ]);
7
8 // Add a new item to the beginning of the collection.
9 $collection->prepend('Select a shirt size');
After the above code has executed, the $collection variable would contain a value similar to
the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=6)
4 0 => string 'Select a shirt size' (length=19)
5 1 => string 'XS' (length=2)
6 2 => string 'S' (length=1)
7 3 => string 'M' (length=1)
8 4 => string 'L' (length=1)
9 5 => string 'XL' (length=2)
The following examples demonstrate the usage of the prepend method when supplying an
argument for the $key parameter:
Collections: The Public API 166
After the above code has executed, the $collection variable would contain a value similar to
the following output:
1 Collection {â–¼
2 #items: array:3 [
3 "size" => "XL"
4 "name" => "Holiday Jumper"
5 "color" => "Red"
6 ]
7 }
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second',
7 'third' => 'I am third'
8 ]);
9
10 // Pull the third value from the collection.
11 $value = $collection->pull('third');
12
13 // null
14 $doesNotExist = $collection->pull('non-existent');
15
16 // default-value
17 $alsoDoesNotExist = $collection->pull('non-existent', 'default-value');
After the above code has executed, the $value variable would contain the value I am third
and the $collection variable would contain a value similar to the following output:
Collections: The Public API 167
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=2)
4 'first' => string 'I am first' (length=10)
5 'second' => string 'I am second' (length=11)
9.34 push($value)
The push method is the logical opposite of the prepend method and will push an item onto the
end of the collection. The push method returns a reference to the original collection instance.
The following code example shows how to use the push method to put an item on the end of the
collection:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'I am first',
6 'I am second'
7 ]);
8
9 // Push an item onto the collection.
10 $collection->push('I am third');
After the above code has executed, the $collection variable would contain a value similar to
the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'I am first' (length=10)
5 1 => string 'I am second' (length=11)
6 2 => string 'I am third' (length=10)
It should be noted that the push method cannot be used to set the key of the item that is being
added to the collection.
The following code example will highlight the usage of the put method:
Collections: The Public API 168
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second'
7 ]);
8
9 // Put a new item in the collection.
10 $collection->put('third', 'I am third');
After the above code has executed, the $collection variable would contain a value similar to
the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=3)
4 'first' => string 'I am first' (length=10)
5 'second' => string 'I am second' (length=11)
6 'third' => string 'I am third' (length=10)
9.36 random($amount = 1)
The random method will retrieve a random $amount of items from the collection. By default,
the random method will return only one item, however a different $amount can be passed in
to change the number of items returned. If the number of items returned is greater than one, a
Collection instance is returned. If the number of items returned is exactly one, the individual
item will be returned. If the $amount of items requested exceeds the total number of items in
the collection, an InvalidArgumentException will be thrown.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second',
7 'third' => 'I am third'
8 ]);
9
10 // Randomly retrieve a single item.
11 $random = $collection->random();
12
13 // Randomly retrieve a collection of items. The
14 // returned value will be a Collection instance.
15 $randomItems = $collection->random(2);
Collections: The Public API 169
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 1, 2, 3, 4, 5
6 ]);
7
8 // 15
9 $sum = $collection->reduce(function($carry, $item) {
10 return $carry + $item;
11 });
12
13 // -15
14 $difference = $collection->reduce(function($carry, $item) {
15 return $carry - $item;
16 });
The following sample will show how to get the product of each item in the collection. It will also
prove a good use case for the $initial parameter:
1 // 0
2 $product = $collection->reduce(function($carry, $item) {
3 return $carry * $item;
4 });
The above example returns 0 which might not seem obvious when the expected answer is 120.
However, the $initial is used as the $carry argument for the first iteration of the $callback
function. The $initial value is null by default. When null is used for mathematical
operations in PHP, it is treated as the value 0:
Collections: The Public API 170
1 // 0
2 $value = intval(null);
Because of this, the multiplication looks like this for each iteration (the result will become the
carry value for the next iteration):
The result is 0, because multiplying any value by zero will result in zero (the multiplication
property of zero). To get the desired answer, the $initial value must be set to 1:
1 // 120
2 $product = $collection->reduce(function($carry, $item) {
3 return $carry * $item;
4 }, 1);
The following table shows the iterations using the change made above:
9.38 reject($callback)
The reject method used to create a new Collection instance containing all the items in the
collection that do not pass a given truth test. The reject method only defines one parameter:
$callback. The $callback function should only have one parameter $item, which will contain
the collection item under test. The $callback should return true if the item should not be
included in the final collection.
To put it another way, the $callback function answers the question “Should I remove this item
from the collection?” true means it will be removed, false indicates that it should remain in
the collection.
The following code example demonstrates the usage of the reject method by rejecting any
name that does not begin with the letter a (ignoring case):
Collections: The Public API 171
1 use Illuminate\Support\Collection;
2 use Illuminate\Support\Str;
3
4 // Create a new collection instance.
5 $collection = new Collection([
6 'Alice', 'Anna', 'Bob', 'Bev'
7 ]);
8
9 // Only keep names that begin with the letter 'a'.
10 $names = $collection->reject(function($item), {
11 return !Str::startsWith(Str::lower($item), 'a');
12 });
After the above code executes, the $names variable will be an instance of Collection and
contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[136]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'Alice' (length=5)
5 1 => string 'Anna' (length=4)
9.39 reverse
The reverse method is used to reverse the order of items in a collection. The reverse method
returns a new Collection instance. The reverse method does not preserve numerical keys
but will preserve non-numerical keys.
The following code example highlights the usage of the reverse method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 $reversed = $collection->reverse();
The $reversed variable would now hold an instance of Collection and would contain a value
similar to the following output:
Collections: The Public API 172
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'third' (length=5)
5 1 => string 'second' (length=6)
6 2 => string 'first' (length=5)
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third', 4
6 ]);
7
8 // 3
9 $key = $collection->search('4');
10
11 // 0
12 $key = $collection->search('first');
13
14 // false
15 $key = $collection->search('fourth');
The following code example will demonstrate the affect of the $strict parameter:
1 // false
2 $key = $collection->search('4', true);
3
4 // 3
5 $key = $collection->search(4, true);
Collections: The Public API 173
9.41 shift
The shift method is used to remove the first item from the collection and return its value. The
shift method modifies the collection instance. The following code example shows how to use
the shift method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // first
9 $firstValue = $collection->shift();
After the above code has executed, the first item from the collection will have been removed.
The final value of the $collection variable would be similar to the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'second' (length=6)
5 1 => string 'third' (length=5)
9.42 shuffle
The shuffle method is used to rearrange the items of the array in a random distribution. The
shuffle method will return a new collection and will not modify the original collection instance.
The following code example shows the usage of the shuffle method. The output will change
each time the code is ran, so the output is unlikely to match the example output on the first try:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // Shuffle the collection.
9 $shuffled = $collection->shuffle();
After the above code sample has executed, the $shuffled variable will be an instance of
Collection and will contain a value similar to the following output (likely with a different
order):
Collections: The Public API 174
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'third' (length=5)
5 1 => string 'second' (length=6)
6 2 => string 'first' (length=5)
The slice method is used to return a slice, or portion of the collection starting at the given
$offset. The $offset tells the slice method where to begin when creating the collection.
For example, if the $offset is 3, the new collection will begin with the third item in the
collection. If the $offset is negative, the new collection will start that distance from the end of
the collection. The slice method returns a new Collection instance and will not modify the
original Collection instance.
The following code example demonstrates the usage of the slice method using a simple
collection:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([1, 2, 3, 4, 5 , 6, 7, 8]);
5
6 // Slice the collection starting at the third item.
7 // The returned collection will contain items
8 // 4, 5, ,7 and 8.
9 $sliced = $collection->slice(3);
After the above code has executed the $sliced variable will be an instance of Collection and
contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=5)
4 0 => int 4
5 1 => int 5
6 2 => int 6
7 3 => int 7
8 4 => int 8
The same result can be accomplished using a negative $offset like so:
Collections: The Public API 175
After the above code has executed, like before, the $sliced variable would be an instance of
Collection and would contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=5)
4 0 => int 4
5 1 => int 5
6 2 => int 6
7 3 => int 7
8 4 => int 8
The $length parameter allows developers to control the size of the returned Collection. If the
provided $length is positive, the returned collection will have up that many items. The total
number of items can be less than the supplied $length if the original collection does not have
enough items to satisfy the $length. If the $length is negative, the returned collection will
stop that many items from the end of the original collection. The following example shows the
various uses of the $length parameter using the $collection instance created earlier:
By default, the slice method will reorder and reset the keys of the returned collection’s items.
This can be changed by passing true as the argument for the $preserveKeys parameter. The
following code samples show the affect of the $preserveKeys parameter:
Collections: The Public API 176
After the above code has executed, the $sliced variable will be an instance of Collection and
contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => int 3
5 1 => int 4
6 2 => int 5
Notice that the keys of the collection are 0, 1 and 2. The following output is for the $preserved-
KeySlice variable (which is also an instance of Collection). Notice how the keys are 2, 3 and
4, because they were preserved:
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=3)
4 2 => int 3
5 3 => int 4
6 4 => int 5
The following example highlights the use of the sort method without supplying a user-defined
comparison function (by providing an argument for $callback):
Collections: The Public API 177
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([8, 4, 6, 2, 7, 5, 1, 3]);
5
6 // Sort the collection.
7 $sorted = $collection->sort();
After the above code has executed, the $sorted variable will be an instance of Collection and
contain a value similar to the following output (notice the order of the collection’s items):
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=8)
4 6 => int 1
5 3 => int 2
6 7 => int 3
7 1 => int 4
8 5 => int 5
9 2 => int 6
10 4 => int 7
11 0 => int 8
It should also be noted that the sort method preserves the keys of the collection items when
sorting.
After the above code has executed, the $sorted variable will be an instance of Collection and
contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=8)
4 0 => int 8
5 4 => int 7
6 2 => int 6
7 5 => int 5
8 1 => int 4
9 7 => int 3
10 3 => int 2
11 6 => int 1
A more practical example would be to sort a collection of people based on their age:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['name' => 'Sue', 'age' => 23],
6 ['name' => 'Simon', 'age' => 38],
7 ['name' => 'Jane', 'age' => 25],
8 ['name' => 'Dave', 'age' => 19]
9 ]);
10
11 // Sort the collection based on a person's age.
12 $sorted = $collection->sort(function($a, $b) {
13 if ($a['age'] == $b['age']) {
14 return 0;
15 }
16
17 return ($a['age'] < $b['age']) ? -1 : 1;
18 });
After the above code has executed, the $sorted variable will be an instance of Collection and
contain a value similar to the following output:
Collections: The Public API 179
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=4)
4 3 =>
5 array (size=2)
6 'name' => string 'Dave' (length=4)
7 'age' => int 19
8 0 =>
9 array (size=2)
10 'name' => string 'Sue' (length=3)
11 'age' => int 23
12 2 =>
13 array (size=2)
14 'name' => string 'Jane' (length=4)
15 'age' => int 25
16 1 =>
17 array (size=2)
18 'name' => string 'Simon' (length=5)
19 'age' => int 38
The sortBy method is useful and versatile way to sort collections by some key, or by some value
returned by a $callback. The $callback can either be a function that defines two parameters:
$value and $key or the $callback can be the name of some key to sort the collection by. The
$options parameter allows developers to modify the sorting behavior and the $descending
parameter controls whether or not the sortBy method will sort the collection ascending (false)
or descending (true). The sortBy method does not modify the original collection instance, but
will return a new instance of Collection with the items sorted.
The following collection of imaginary users will be used when demonstrating the features of the
sortBy method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 [
6 'name' => 'Sue',
7 'age' => 23,
8 'followers' => [
9 'Jim',
10 'Donna'
11 ]
Collections: The Public API 180
12 ],
13 [
14 'name' => 'Simon',
15 'age' => 38,
16 'followers' => [
17 'Sue'
18 ]
19 ],
20 [
21 'name' => 'Jane',
22 'age' => 25,
23 'followers' => [
24 'Link',
25 'Dave',
26 'Chase'
27 ]
28 ],
29 [
30 'name' => 'Dave',
31 'age' => 19,
32 'followers' => [
33 'Dee Dee',
34 'Stevie'
35 ]
36 ]
37 ]);
The $sorted variable would now be an instance of Collection and the items would be in the
following order:
1 Dave
2 Jane
3 Simon
4 Sue
1 Sue
2 Simon
3 Jane
4 Dave
The users can also be sorted by the number of followers they have. To accomplish this, a callback
function must be used:
1 Simon
2 Sue
3 Dave
4 Jane
Of course, it is often desirable to see which users have the most followers. To do this, use the
same techniques as before to change the sort order to descending:
⁸http://php.net/manual/en/function.sort.php
Collections: The Public API 182
1 use Illuminate\Support\Collection;
2
3
4 /**
5 * A simple class to represent an animal.
6 *
7 * Its only purpose to accept the name of the
8 * animal and return it when the object
9 * instance is cast to a string.
10 */
11 class Animal {
12
13 /**
14 * The name of the animal.
15 *
16 * @var string
17 */
18 private $name = '';
19
20 public function __construct($name) {
21 $this->name = $name;
22 }
23
24 public function __toString() {
25 return $this->name;
26 }
27
28 }
29
30 // Create a new collection instance.
31 $collection = new Collection([
32 0 => 'a2.txt',
33 1 => 'a1.txt',
34 2 => 'a4.txt',
35 3 => new Animal('KANGAROO'),
36 4 => new Animal('kangaroo'),
37 5 => 'a3.txt',
38 6 => 6,
39 7 => 5,
40 8 => new Animal('macaw'),
41 9 => 'candice',
42 10 => 'bob',
43 11 => 'alice',
44 12 => new Animal('zebra')
45 ]);
Collections: The Public API 183
The $collection contains a diverse range of items. It contains strings, integers and a few
Animal instances. The keys of each item have also been explicitly set. This will make it easier to
keep track of where each item has moved after the collection is sorted.
The following sort flags are available when using the sortBy method:
Flag Description
SORT_REGULAR This is the default sorting flag. It compares each item normally, without
changing the type of each item when comparing.
SORT_NUMERIC This flag will cause each item to be treated as a number when doing the
comparison.
SORT_STRING This flag will cause each item to be treated as a string when doing the
comparison.
SORT_LOCALE_STRING This flag will cause each item to be treated as a string when doing the
comparison, but will also take into account PHP’s current locale.
SORT_NATURAL This flag compares each item a string, using a “natural ordering” sorting
algorithm, similar to the sort method when working with collections.
SORT_FLAG_CASE Can be combined with the SORT_STRING and SORT_NATURAL flags to sort
the strings in a case-insensitive way.
The following tables will show how the different sorting flags change the sorting of the
previously made $collection. Each sorting flag has its own section, which will follow this
section. The first table shows the key and its associated value from the original collection,
which can be used to locate the original item from the table that follows. The table that follows
shows each sorting flag and the sorting order that would result from using that sorting flag. The
collection was sorted by using the string representation of the item’s value.
Original Order 0 1 2 3 4 5 6 7 8 9 10 11 12
SORT_REGULAR 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_NUMERIC 8 9 10 11 0 5 2 1 3 4 12 7 6
SORT_STRING 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_STRING | SORT_FLAG_CASE 7 6 1 0 5 2 11 10 9 4 3 8 12
SORT_LOCALE_STRING 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_NATURAL 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_NATURAL | SORT_FLAG_CASE 7 6 1 0 5 2 11 10 9 4 3 8 12
9.45.1.2 SORT_NUMERIC
The SORT_NUMERIC treats each item as a number when doing the comparison. The following
code example shows how to use the SORT_NUMERIC flag when sorting the $collection created
previously (the callback function will return the string representation of the item):
The following table will use each item’s key to represent the new sort order. It will compare the
original collection order, the order when using the SORT_REGULAR flag and the order when using
the SORT_NUMERIC flag.
Original Order 0 1 2 3 4 5 6 7 8 9 10 11 12
SORT_REGULAR 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_NUMERIC 8 9 10 11 0 5 2 1 3 4 12 7 6
9.45.1.3 SORT_STRING
The SORT_STRING treats each item as a string when doing the comparison. The following
code example shows how to use the SORT_STRING flag when sorting the $collection created
previously (the callback function will return the string representation of the item):
The following table will use each item’s key to represent the new sort order. It will compare the
original collection order, the order when using the SORT_REGULAR flag and the order when using
the SORT_STRING flag.
Collections: The Public API 185
Original Order 0 1 2 3 4 5 6 7 8 9 10 11 12
SORT_REGULAR 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_STRING 7 6 3 1 0 5 2 11 10 9 4 8 12
The SORT_FLAG_CASE flag can be combined with the SORT_STRING flag to treat each item
as a string while also ignored the case of each item. The following example shows how to
use the SORT_STRING with the SORT_FLAG_CASE flag when sorting the $collection created
previously (the callback function will return the string representation of the item):
The following table will use each item’s key to represent the new sort order. It will compare the
original collection order, the order when using the SORT_STRING flag and the order when using
the SORT_STRING combined with the SORT_FLAG_CASE flag.
Original Order 0 1 2 3 4 5 6 7 8 9 10 11 12
SORT_STRING 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_STRING | SORT_FLAG_CASE 7 6 1 0 5 2 11 10 9 4 3 8 12
9.45.1.4 SORT_LOCALE_STRING
The SORT_LOCALE_STRING treats each item as a string, while also taking into account the current
locale, when doing the comparison. The following code example shows how to use the SORT_-
LOCALE_STRING flag when sorting the $collection created previously (the callback function
will return the string representation of the item):
The following table will use each item’s key to represent the new sort order. It will compare the
original collection order, the order when using the SORT_REGULAR flag and the order when using
the SORT_LOCALE_STRING flag.
Collections: The Public API 186
Original Order 0 1 2 3 4 5 6 7 8 9 10 11 12
SORT_REGULAR 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_LOCALE_STRING 7 6 3 1 0 5 2 11 10 9 4 8 12
9.45.1.5 SORT_NATURAL
The SORT_NATURAL treats each item as a string while using a “natural ordering” algorithm to
perform the sorting. The following code example shows how to use the SORT_NATURAL flag
when sorting the $collection created previously (the callback function will return the string
representation of the item):
The following table will use each item’s key to represent the new sort order. It will compare the
original collection order, the order when using the SORT_REGULAR flag and the order when using
the SORT_NATURAL flag.
Original Order 0 1 2 3 4 5 6 7 8 9 10 11 12
SORT_REGULAR 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_NATURAL 7 6 3 1 0 5 2 11 10 9 4 8 12
The SORT_FLAG_CASE flag can be combined with the SORT_NATURAL flag to treat each item
as a string while also ignored the case of each item. The following example shows how to
use the SORT_NATURAL with the SORT_FLAG_CASE flag when sorting the $collection created
previously (the callback function will return the string representation of the item):
The following table will use each item’s key to represent the new sort order. It will compare the
original collection order, the order when using the SORT_NATURAL flag and the order when using
the SORT_NATURAL combined with the SORT_FLAG_CASE flag.
Collections: The Public API 187
Original Order 0 1 2 3 4 5 6 7 8 9 10 11 12
SORT_NATURAL 7 6 3 1 0 5 2 11 10 9 4 8 12
SORT_NATURAL | SORT_FLAG_CASE 7 6 1 0 5 2 11 10 9 4 3 8 12
The following calls to the sortBy and sortByDesc methods are functionally equivalent:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['name' => 'Marshall']
6 ]);
7
8 $sorted = $collection->sortBy('name', SORT_REGULAR, true);
9
10 $sorted = $collection->sortByDesc('name', SORT_REGULAR);
11
12 $sorted = $collection->sortByDesc('name');
The splice method is a versatile method; it is often used to remove a portion of a collection and
return the removed section. It defines three parameters: $offset, $length and $replacement.
The $offset tells the splice method where to begin when removing items from the collection.
For example, if the $offset is 3, the all items beginning with the third item in the collection
will be removed. If the $offset is negative, items will be removed that are that distance from
the end of the collection. The splice method modifies the original Collection instance and
returns the removed items as a new Collection instance.
The following example shows the basic usage of the splice method:
Collections: The Public API 188
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 0, 1, 2 ,3 , 4, 5, 6, 7 ,8
6 ]);
7
8 // Splice the $collection starting with the third item.
9 $spliced = $collection->splice(3);
After the above has executed, the $spliced variable will be an instance of Collection and
contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=6)
4 0 => int 3
5 1 => int 4
6 2 => int 5
7 3 => int 6
8 4 => int 7
9 5 => int 8
The $collection variable will also have been modified, and will now contain a value similar
to the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=3)
4 0 => int 0
5 1 => int 1
6 2 => int 2
The $length parameter can be used to control how long the section that is removed from
the collection can be. The following example demonstrates how to remove four items from the
collection, starting with the third item:
Collections: The Public API 189
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 0, 1, 2 ,3, 4 , 5, 6, 7 ,8
6 ]);
7
8 // Splice the $collection starting with the third item
9 // and take at most 4 items.
10 $spliced = $collection->splice(3, 4);
After the above example has executed, the $spliced variable will again be an instance of
Collection and contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=4)
4 0 => int 3
5 1 => int 4
6 2 => int 5
7 3 => int 6
Like before, the $collection variable will have been modified and now contain a value similar
to the following output:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=5)
4 0 => int 0
5 1 => int 1
6 2 => int 2
7 3 => int 7
8 4 => int 8
The $replacement parameter can be utilized to replace the items removed from the collection.
When using the $replacement parameter, the items removed from the collection are still
returned as a new instance of Collection. Any argument passed for $replacement must be
an array, or must be able to be cast into an array. Any keys from the $replacement array will
not be preserved when added to the collection.
The following example shows how to use the $replacement parameter:
Collections: The Public API 190
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third', 'fourth'
6 ]);
7
8 // Replace all items beginning with the second.
9 $spliced = $collection->splice(1, 3, [
10 '2nd', '3rd', '4th'
11 ]);
After the above code has executed, the $spliced variable will be an instance of Collection
and contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'second' (length=6)
5 1 => string 'third' (length=5)
6 2 => string 'fourth' (length=6)
The $collection variable will also have been modified, but instead of just removing items, the
new items 2nd, 3rd and 4th will have been inserted into the collection in place of the items that
were removed:
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=4)
4 0 => string 'first' (length=5)
5 1 => string '2nd' (length=3)
6 2 => string '3rd' (length=3)
7 3 => string '4th' (length=3)
After the above code has executed $average would contain the value 12.5, which is the average
of 5, 10, 15, and 20.
The previous example was fairly simple, and in most cases the collections will be more
complicated. For example, consider the following sample collection of products:
1 $products = collect([
2 ['name' => 'Shiny New Tablet', 'price' => 799.99],
3 ['name' => 'Not A Stylus (Digital Stylus)', 'price' => 99.99]
4 ]);
We can calculate the average price of all items in the collection by simply passing in a value for
the $key parameter. The value of $key must correspond to some key or property of the nested
arrays or objects:
After the above code has been executed, the $averagePrice variable would contain the value
449.99.
The avg method will also work on collections of objects, and is used exactly the same way. If
we created a new collection of products, where all the individual products are objects instead of
nested arrays, we will get the same result:
Now we can call the avg method on our new $objectProducts collection:
Like before, the value of $objectAveragePrice would contain the value 449.99.
As with all the previous examples, the $averageProductPrice variable would contain the
value 449.99.
1 // Results in 12.5
2 collect([5, 10, 15, 20])->avg();
3
4 // Results in 12.5
5 collect([5, 10, 15, 20])->average();
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 1, 2, 3, 4, 5
6 ]);
7
8 // 15
9 $sum = $collection->sum();
After the above code has executed, the $sum variable will contain the value 15, which is indeed
the sum of all the items in the collection.
The following is a more interesting example, and shows the total number of speakers at Laracon
EU for the years 2013, 2014 and 2015. The number of speakers is not unique, and therefore not
technically accurate:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['year' => '2015', 'speakers' => 12],
6 ['year' => '2014', 'speakers' => 21],
7 ['year' => '2013', 'speakers' => 10]
8
9 ]);
10
11 // 43
12 $totalSpeakers = $collection->sum('speakers');
After the above code has executed, the $totalSpeakers variable would contain the value 43.
The following collection also contains the number of speakers that spoke Laracon EU from 2013
to 2015, but instead of representing the speakers as number, the collection contains lists the names
of the speakers.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 [
6 'year' => '2015',
7 'speakers' => [
8 'Jeffrey',
9 'Taylor',
10 'Matt',
Collections: The Public API 194
11 'Konstantin',
12 'Jessica',
13 'Frank',
14 'Adam',
15 'Lorna',
16 'Dries',
17 'Ben',
18 'Esther',
19 'Hannes'
20 ]
21 ],
22 [
23 'year' => '2014',
24 'speakers' => [
25 'Taylor',
26 'Ross',
27 'Erika',
28 'Konstantin',
29 'Andreas',
30 'Kayla',
31 'Matthias',
32 'Mathias',
33 'Ben',
34 'Rafael',
35 'Igor',
36 'Michelle',
37 'Adam',
38 'Xander',
39 'Wim',
40 'Mitchell',
41 'Gabriela',
42 'Matt',
43 'Frank',
44 'Hannes',
45 'Kirk'
46 ]
47 ],
48 [
49 'year' => '2013',
50 'speakers' => [
51 'Taylor',
52 'Fabien',
53 'Phill',
54 'Jordi',
55 'Kapil',
56 'Matthew',
Collections: The Public API 195
57 'Frank',
58 'Jeffrey',
59 'Ben',
60 'Ross'
61 ]
62 ]
63 ]);
The total number of speakers can be counted using the sum method by passing a function as the
argument to the $callback parameter. The callback function passed must define one parameter,
which will be the value of the item. The following code example shows how to get the sum of
all the speakers in the above collection:
1 // 43
2 $totalSpeakers = $collection->sum(function($value) {
3 return count($value['speakers']);
4 });
After the above code has executed, the value of $totalSpeakers will be 43, just as it was in the
previous example. It is important to note that the callback function should return a numerical
value, and in the above example it is returning the result of the count function.
9.51 take($limit)
The take method is a useful method that will return a number of items (up to the provided
$limit) from the collection. If the $limit is negative, it will return a number of items (up to
the provided $limit) from the end of the collection, otherwise the items will be returned from
the beginning of the collection. The take method returns a new Collection instance and does
not modify the original collection.
The following example demonstrates the usage of the take method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third', 'fourth'
6 ]);
7
8 // Take two items from the beginning of the collection.
9 $positiveLimit = $collection->take(2);
10
11 // Take two items from the end of the collection.
12 $negativeLimit = $collection->take(-2);
After the above code has executed both $positiveLimit and $negativeLimit will be an
instance of Collection. The $positiveLimit variable will contain a value similar to the
following output:
Collections: The Public API 196
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'first' (length=5)
5 1 => string 'second' (length=6)
And the $negativeLimit variable will contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'third' (length=5)
5 1 => string 'fourth' (length=6)
9.52 toJson($options = 0)
The toJson method will return a JSON encoded version of the data stored within the collection
instance. It internally does this by returning a call to PHP’s json_encode⁹ function, passing in
any $options that were supplied. Like the json_encode function, the $options parameter is
a bitmask of the predefined JSON constants¹⁰.
After the above code executes, $jsonValue would contain the following value:
1 [{"name":"Shirley","age":60},{"name":"John","age":55}]
⁹http://php.net/manual/en/function.json-encode.php
¹⁰http://php.net/manual/en/json.constants.php
Collections: The Public API 197
1 [
2 {
3 "name": "Shirley",
4 "age": 60
5 },
6 {
7 "name": "John",
8 "age": 55
9 }
10 ]
The toJson method internally makes a call to PHP’s json_encode function. Unlike json_-
encode, toJson does not provide a way to specify the depth (essentially how many arrays
are nested inside of each other) to which data will be encoded, which is by default set to 512.
To convert a collection instance into its JSON equivalent with a depth greater than 512, the
following method will be sufficient:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([]);
5
6 // Replace 512 with the desired depth.
7 $jsonValue = json_encode($collection->jsonSerialize(), 0, 512);
9.53 __toString()
When a Collection instance is cast into a string, its JSON representation is returned as the
result. Internally this is accomplished by returning the results of the collection’s toJson method.
Collections: The Public API 198
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'name' => 'Flo'
6 ]);
7
8 // Cast the collection to a string.
9 $stringValue = (string) $collection;
After the above code has executed, the $stringValue variable will contain the following value:
1 {"name":"Flo"}
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'first', 'second', 'third'
6 ]);
7
8 // Modify the original and change the case of
9 // each string to upper-case.
10 $collection->transform(function($item, $key) {
11 return strtoupper($item);
12 });
After the above code example has executed, the $collection variable would would contain a
value similar to the following output:
Collections: The Public API 199
1 object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'FIRST' (length=5)
5 1 => string 'SECOND' (length=6)
6 2 => string 'THIRD' (length=5)
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'a', 'A', 'b', 'c', 1, 1, 2, 3
6 ]);
7
8 // Get all unique items.
9 $uniqueItems = $collection->unique();
After the above code executes, the $uniqueItems variable will be an instance of Collection
and will have a value similar to the following output. It should be noted that the unique method
is case sensitive.
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=7)
4 0 => string 'a' (length=1)
5 1 => string 'A' (length=1)
6 2 => string 'b' (length=1)
7 3 => string 'c' (length=1)
8 4 => int 1
9 6 => int 2
10 7 => int 3
The following code sample demonstrates how to use the unique method to get all the unique
items in a collection based on a given property of the collection’s items (in this example it is the
name of hypothetical users):
Collections: The Public API 200
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 ['id' => 5, 'name' => 'Jane', 'sex' => 'female'],
6 ['id' => 6, 'name' => 'Bill', 'sex' => 'male'],
7 ['id' => 7, 'name' => 'Sarah', 'sex' => 'female'],
8 ['id' => 8, 'name' => 'Sarah', 'sex' => 'female']
9 ]);
10
11 // Get all unique items.
12 $uniqueItems = $collection->unique('name');
After the above code has finished executing the $uniqueItems variable will be an instance of
Collection and will have a value similar to the following output:
1 object(Illuminate\Support\Collection)[137]
2 protected 'items' =>
3 array (size=3)
4 0 =>
5 array (size=3)
6 'id' => int 5
7 'name' => string 'Jane' (length=4)
8 'sex' => string 'female' (length=6)
9 1 =>
10 array (size=3)
11 'id' => int 6
12 'name' => string 'Bill' (length=4)
13 'sex' => string 'male' (length=4)
14 2 =>
15 array (size=3)
16 'id' => int 7
17 'name' => string 'Sarah' (length=5)
18 'sex' => string 'female' (length=6)
The provided $key can also be a callback function that accepts one argument. The argument
will be the item from the collection. The callback function should return the value the unique
method uses to determine uniqueness. The following example is similar to the first example in
this section, but will effectively perform a case-insensitive uniqueness check:
Collections: The Public API 201
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 'a', 'A', 'b', 'c', 1, 1, 2, 3
6 ]);
7
8 // Get all unique items.
9 $uniqueItems = $collection->unique(function($item) {
10 return strtolower($item);
11 });
After the above code has been ran, the $uniqueItems variable will be an instance of Collec-
tion and contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[137]
2 protected 'items' =>
3 array (size=6)
4 0 => string 'a' (length=1)
5 2 => string 'b' (length=1)
6 3 => string 'c' (length=1)
7 4 => int 1
8 6 => int 2
9 7 => int 3
9.56 values
The values method can be used to retrieve a new Collection instance containing only
the values of the original collection instance. The keys of the new collection will be reset to
consecutive numerical keys.
The following example demonstrates the usage of the values method:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 5 => 'five',
6 6 => 'six',
7 7 => 'seven'
8 ]);
9
10 // Get the collection values.
11 $values = $collection->values();
Collections: The Public API 202
After the above code has executed, the $values variable will be an instance of Collection
and contain a value similar to the following output. Take note in how the keys of the associated
values have changed (they have been reset starting at 0):
1 object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'five' (length=4)
5 1 => string 'six' (length=3)
6 2 => string 'seven' (length=5)
1 <?php
2
3 use Illuminate\Support\Collection;
4
5 // Create a new collection.
6 $collection = new Collection([
7 [
8 'genus' => 'Canis',
9 'name' => 'tundra wolf',
10 'age' => '2'
11 ],
12 [
13 'genus' => 'Canis',
14 'name' => 'arctic wolf',
15 'age' => 4
16 ],
17 [
18 'genus' => 'Cucumis',
19 'name' => 'cucumber',
20 'age' => 2
21 ]
22 ]);
23
Collections: The Public API 203
After the above code has executed, the $animals variable will be an instance of Collection
and contain a value similar to the following output:
1 Illuminate\Support\Collection {#478
2 #items: array:2 [
3 0 => array:3 [
4 "genus" => "Canis"
5 "name" => "tundra wolf"
6 "age" => "2"
7 ]
8 1 => array:3 [
9 "genus" => "Canis"
10 "name" => "arctic wolf"
11 "age" => 4
12 ]
13 ]
14 }
An observant reader will notice that the where method was used with only two parameters
used. When the where method is called with only two parameters, such as in where('genus',
'Canis'), the $operator parameter will internally be set to =. This allows the method to
maintain backwards compatibility with older versions of the Collection class.
The where method supports the following operators:
Operator Description
== Ensures equality between the check $value and the key value on the collection item.
This operator does not compare the types of the values.
= Same behavior as ==.
=== Ensures equality between the check $value and the key value on the collection item.
This operator does compare the types of the values.
<> Ensures inequality between the check $value and they key value on the collection item.
This operator does not compare the types of the values.
!== Ensures inequality between the check $value and the key value on the collection item.
This operator does compare the types of the values.
< Ensures that the key value on the collection item is less than the supplied check $value.
> Ensures that the key value on the collection item is greater than the supplied check
$value.
<= Ensures that the key value on the collection item is less than or equal to the supplied
check $value.
>= Ensures that the key value on the collection item is greater than or equal to the supplied
check $value.
Each item in the previous collection contains an age property. Some of these ages are stored as
Collections: The Public API 204
strings, and some are stored as integers. This will be sufficient to show the differences between
the equality operators and how they are affected by type comparisons.
1 <?php
2
3 // ...
4
5 $typeComparisonResults = $collection->where('age', '===', 2);
After the above code has executed, the $typeComparisonResults collection will only contain
one item: the cucumber. This is because the cucumber’s age is represented as an integer, and the
value 2 was passed into the where method as an integer. If the value 2 was passed as a string
the only value returned would have been the tundra wolf.
In Laravel versions 5.2 and below, similar functionality can be achieved using the filter method
(the methods demonstrated below are still relevant for Laravel 5.3, however). The following
example demonstrates how to use comparison operators with the filter method:
1 <?php
2
3 // ...
4
5 // Get all items where the age is
6 // greater than or equal to 4.
7 $filteredResults = $collection->filter(function ($item) {
8 return data_get($item, 'age') >= 4;
9 });
1 use Illuminate\Support\Collection;
2
3 // Create a new collection.
4 $collection = new Collection([
5 [
6 'genus' => 'Canis',
7 'name' => 'tundra wolf',
8 'age' => '2'
9 ],
10 [
11 'genus' => 'Canis',
12 'name' => 'arctic wolf',
13 'age' => 4
14 ],
15 [
16 'genus' => 'Cucumis',
17 'name' => 'cucumber',
18 'age' => 2
19 ]
20 ]);
21
22 $results = $collection->whereLoose('age', 2);
After the above code has executed, the $results variable would an instance of Collection
and contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[136]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 array (size=3)
6 'genus' => string 'Canis' (length=5)
7 'name' => string 'tundra wolf' (length=11)
8 'age' => string '2' (length=1)
9 2 =>
10 array (size=3)
11 'genus' => string 'Cucumis' (length=7)
12 'name' => string 'cucumber' (length=8)
13 'age' => int 2
It can be observed that the two age values have different data types, but were still returned in
the $results collection.
The whereLoose method is a shortcut to calling the where method with optional parameters. In
fact, the following two examples would produce the same results and are functionally equivalent:
Collections: The Public API 206
9.59 zip($items)
The zip method is used to merge the values of the $items array with the values within the
Collection at the corresponding index. The zip method produces results that are similar to
Python’s zip¹¹ function, and developer’s coming from a Python background will recognize the
behavior of the zip method. The zip method returns a new Collection instance and does not
modify the original collection in any way.
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 1, 2, 3
6 ]);
7
8 // Create a new collection by zipping the original
9 // collection with a new array of values.
10 $zipped = $collection->zip([
11 4, 5, 6
12 ]);
After the above code has executed, the $zipped variable will be an instance of Collection and
contain a value similar to the following output:
1 object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=3)
4 0 =>
5 object(Illuminate\Support\Collection)[136]
6 protected 'items' =>
7 array (size=2)
8 0 => int 1
9 1 => int 4
10 1 =>
11 object(Illuminate\Support\Collection)[137]
12 protected 'items' =>
13 array (size=2)
14 0 => int 2
15 1 => int 5
¹¹https://docs.python.org/2/library/functions.html#zip
Collections: The Public API 207
16 2 =>
17 object(Illuminate\Support\Collection)[138]
18 protected 'items' =>
19 array (size=2)
20 0 => int 3
21 1 => int 6
The zip method can accept multiple arguments, and they can be any data type that can be
converted to an array:
1 use Illuminate\Support\Collection;
2
3 // Create a new collection instance.
4 $collection = new Collection([
5 1, 2, 3
6 ]);
7
8 // Create a new collection instance to use an
9 // an argument for the zip method.
10 $testCollection = new Collection([
11 7, 8, 9
12 ]);
13
14 // Notice the call to all() at the end of this
15 // method chain to return the array of
16 // zipped results
17 $zippedResults = $collection->zip(
18 [4, 5, 6],
19 $testCollection,
20 [10, 11],
21 [12, 13, 14, 15]
22 )->all();
After the above code has executed, the $zippedResults variable would contain the following
value:
1 array (size=4)
2 0 =>
3 object(Illuminate\Support\Collection)[137]
4 protected 'items' =>
5 array (size=5)
6 0 => int 1
7 1 => int 4
8 2 => int 7
9 3 => int 10
Collections: The Public API 208
10 4 => int 12
11 1 =>
12 object(Illuminate\Support\Collection)[138]
13 protected 'items' =>
14 array (size=5)
15 0 => int 2
16 1 => int 5
17 2 => int 8
18 3 => int 11
19 4 => int 13
20 2 =>
21 object(Illuminate\Support\Collection)[139]
22 protected 'items' =>
23 array (size=5)
24 0 => int 3
25 1 => int 6
26 2 => int 9
27 3 => null
28 4 => int 14
29 3 =>
30 object(Illuminate\Support\Collection)[140]
31 protected 'items' =>
32 array (size=5)
33 0 => null
34 1 => null
35 2 => null
36 3 => null
37 4 => int 15
There are a few important things to notice in the above output. The [10, 11] array that was
passed as an argument had less items than the other arrays when building the final result. As a
result, the value null was used for the fourth item in the third Collection instance The other
important thing to notice is a result of the [12, 13, 14, 15] argument having more items
that the other arrays.
Because the [12, 13, 14, 15] argument had more items, a new fourth Collection was
created as part of the zipped results. All values were set to null, except for the fifth value,
which was assigned the value 15.
9.60 combine($values)
The combine method is used to combine the keys of the collection the method was called on with
the values of another collection or array (supplied as an argument for $values). This method is
equivalent to using PHP’s array_combine function. This method also returns a new Collection
instance and does not modify the original collection instance.
Collections: The Public API 209
The following example code shows a very simple example of the combine method being used
to combine two simple collections:
After the code has executed, the $combinedCollection variable would have a value similar to
the following:
1 Collection {
2 #items: array:3 [
3 "green" => "avocado"
4 "red" => "apple"
5 "yellow" => "banana"
6 ]
7 }
It is important that both collections/arrays have the same length. If the collections
do not have the same length, an ErrorException will be thrown stating that “Both
parameters should have an equal number of elements”.
You would get the same result if $secondCollection was just a regular PHP array:
We can retrieve all the even numbers using the every method like so:
After the code has executed, the $evenNumbers variable will hold a value similar to the following
output:
1 Collection {
2 #items: array:6 [
3 0 => 0
4 1 => 2
5 2 => 4
6 3 => 6
7 4 => 8
8 5 => 10
9 ]
10 }
As we can see, the returned collection contains all the even numbers from the original collection.
Conversely, we can retrieve all the odd numbers just as easily:
It should be noted that we had to supply an argument for the $offset parameter. So the meaning
of our method call could be interpreted as “get every second item starting with the item at index
1”. After the above example has executed, the $oddNumbers variable will hold a value similar
to the following output:
1 Collection {
2 #items: array:5 [
3 0 => 1
4 1 => 3
5 2 => 5
6 3 => 7
7 4 => 9
8 ]
9 }
Here is another simple example that returns every 50th item from a collection of numbers ranging
from 0 to 1000:
Collections: The Public API 211
After the code has executed, $subset would contain a value similar to the following output:
1 Collection {
2 #items: array:21 [
3 0 => 0
4 1 => 50
5 2 => 100
6 3 => 150
7 4 => 200
8 5 => 250
9 6 => 300
10 7 => 350
11 8 => 400
12 9 => 450
13 10 => 500
14 11 => 550
15 12 => 600
16 13 => 650
17 14 => 700
18 15 => 750
19 16 => 800
20 17 => 850
21 18 => 900
22 19 => 950
23 20 => 1000
24 ]
25 }
9.62 except($keys)
The except method will return all the key/value pairs in the collection where the keys in
the collection are not in the supplied $keys array. Internally, this method makes a call to the
Illuminate\Support\Arr:except($array, $keys) helper function.
After the above code has executed, the $data variable would contain a value similar to the
following output:
1 Collection {
2 #items: array:2 [
3 "first_name" => "John"
4 "last_name" => "Doe"
5 ]
6 }
We can also combine the except method with the toJson method to easily remove sensitive
data from information before sending it to an end user:
1 $jsonData = $collection->except(['password'])->toJson();
After the above code has executed, the $jsonData variable would hold a value similar to the
following JSON string:
1 "{"first_name":"John","last_name":"Doe"}"
9.63 only($keys)
The only method is the logical opposite of the except method. The only method is used to
return all the key/value pairs in the collection where the keys in the collection are in the supplied
$keys array. Internally, this method makes a call to the Illuminate\Support\Arr::only($array,
$keys) helper function.
Using the same example from the except method section, we can get only the first_name and
last_name of the users in a collection:
Collections: The Public API 213
After the above code has executed, the $data variable would contain a value similar to the
following output:
1 Collection {
2 #items: array:2 [
3 "first_name" => "John"
4 "last_name" => "Doe"
5 ]
6 }
9.64 keyBy($keyBy)
The keyBy method is used to create a new Collection instance where the keys of the new
key/value pairs are determined by a $keyBy callback function (a string value can also be
supplied instead of a function). The signature of the callback function is keyBy($item), where
the $item is the actual item in the collection. This method does not change the original
Collection instance will will return a new, modified, Collection instance.
The following sample will be used to demonstrate the keyBy method:
In the following example, we will create a new collection instance where the key of each item is
the persons id. We will not supply a callback function in this example, but rather pass the name
of the value we want to use as the key as as string:
1 $results = $people->keyBy('id');
After the above code has executed, the $results variable will contain a value similar to the
following output:
Collections: The Public API 214
1 Collection {
2 #items: array:3 [
3 12 => array:3 [
4 "id" => 12
5 "name" => "Alice"
6 "age" => 26
7 ]
8 52 => array:3 [
9 "id" => 52
10 "name" => "Bob"
11 "age" => 34
12 ]
13 14 => array:3 [
14 "id" => 14
15 "name" => "Chris"
16 "age" => 26
17 ]
18 ]
19 }
We can also achieve the exact same results by using a callback function like so:
1 $results = $people->keyBy(function($item) {
2 return $item['id'];
3 });
However, the above example is overly complicated if all we were interested in was just the id
of the person. We could do something a little more interesting, such as returning a simple hash
of each persons id to use as the new key:
1 $results = $people->keyBy(function($item) {
2 return md5($item['id']);
3 });
After the above code has executed, the new $results variable would contain a value similar to
the following output:
Collections: The Public API 215
1 Collection {
2 #items: array:3 [
3 "c20ad4d76fe97759aa27a0c99bff6710" => array:3 [
4 "id" => 12
5 "name" => "Alice"
6 "age" => 26
7 ]
8 "9a1158154dfa42caddbd0694a4e9bdc8" => array:3 [
9 "id" => 52
10 "name" => "Bob"
11 "age" => 34
12 ]
13 "aab3238922bcc25a6f606eb525ffdc56" => array:3 [
14 "id" => 14
15 "name" => "Chris"
16 "age" => 26
17 ]
18 ]
19 }
The same method could just as easily be applied to other hashing libraries, such as the
hashids.php¹² library.
We can quickly get a subset of the $people collection based on their age. Assuming we wanted
to retrieve all people whose age was 26 we could use the whereIn method like so:
¹²https://github.com/ivanakimov/hashids.php
Collections: The Public API 216
After the above code has executed, the $results variable will contain a value similar to the
following output:
1 Collection {
2 #items: array:2 [
3 0 => array:2 [
4 "name" => "Alice"
5 "age" => 26
6 ]
7 2 => array:2 [
8 "name" => "Chris"
9 "age" => 26
10 ]
11 ]
12 }
To see the effects of the $strict argument, we can change the above example only slightly to
cause the method to return no results:
Because the age of each person in the $people array is an integer and the item in the $values
array in the previous code example is a string, the $results variable would be an empty
Collection instance. To get this to work, simply pass false as the argument for the $strict
parameter:
After the above code has executed, the $results variable would the same items as in our first
example (both Alice and Chris would be returned).
an item is present in a collection (this can be modified by supplying a third argument to the
whereIn method). The whereInLoose method exists as a shortcut to using the whereIn method,
removing the need of an optional third argument. This method does not change the original
Collection instance and will return a new, modified, Collection instance.
1 $people = collect([
2 ['name' => 'Alice', 'age' => 26],
3 ['name' => 'Bob', 'age' => 34],
4 ['name' => 'Chris', 'age' => 26]
5 ]);
1 use Illuminate\Support\Collection;
2
3 $items = [
4 'sea' => 'Mosasaurus',
5 'air' => 'Argentavis magnificens',
6 'land' => 'Dusicyon australis'
7 ];
8
9 $collection = Collection::make($items);
10
11 // true
12 $isCollection = $collection instanceof Collection;
218
III Additional Helper Classes and
Features
“If I am remembered at all, I would like to be remembered as my family storyteller. It has been a
great life.”
– Kay McNulty (1921 - 2006), Computer Programmer
11. Message Bags
The Illuminate\Suport\MessageBag class is an elaborate key/value storage system for
storing different types of messages. It it also allows developers to specify a format which is
used when returning the messages. The format makes it incredibly simple to format mes-
sages on HTML forms, emails, etc. The MessageBag class implements both the Illumi-
nate\Contracts\Support\MessageProvider and Illuminate\Contracts\Support\MessageBag
interfaces.
11.1 Illuminate\Contracts\Support\MessageProvider
Interface
The MessageProvider interface defines only one method, getMessageBag. The expected
behavior of the getMessageBag method is to return an instance of an implementation of
the Illuminate\Contracts\Support\MessageBag interface. Any class that implements the
MessageProvider interface can be expected to be capable of returning MessageBag implemen-
tations.
The following classes extend, implement, or make use of the MessageProvider interface by
default:
Class Description
Illuminate\Contracts\Validation\ The ValidationException is often thrown
ValidationException when a validation error occurs by some process
within an applications request life-cycle.
Illuminate\Contracts\Validation\ The Validator interface defines the methods
Validation and behaviors of the frameworks validator
component. The Validator component actually
extends the MessageProvider interface.
Illuminate\Http\RedirectResponse The RedirectReponse class is responsible for
setting the correct headers required to redirect a
user’s browser to another URL.
IlluminateSupportMessageBag The MessageBag class is the default
implementation of the
Illuminate\Contracts\Support\MessageBag
interface. It also implements the
MessageProvider interface to return a
reference to itself.
Illuminate\View\View The View class uses instances of
MessageProvider implementations to facilitate
the communication of errors between the
application logic and the front-end code of an
application.
220
Message Bags 221
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add new messages to the message bag.
7 $messageBag->add('hello', 'The first message bag message');
8 $messageBag->add('world', 'The second message');
9
10 // Get an array of all the messages.
11 $messages = $messageBag->getMessages();
After the above code has executed, the $messages variable will be an array and contain a value
similar to the following output:
1 array (size=2)
2 'hello' =>
3 array (size=1)
4 0 => string 'The first message bag message' (length=29)
5 'world' =>
6 array (size=1)
7 0 => string 'The second message' (length=18)
The add method allows multiple messages to be stored under a given $key as long as the
key/message pair is unique. As an example, another message can be supplied for the hello
key like so:
1 array (size=2)
2 'hello' =>
3 array (size=2)
4 0 => string 'The first message bag message' (length=29)
5 1 => string 'This is a different hello' (length=25)
6 'world' =>
7 array (size=1)
8 0 => string 'The second message' (length=18)
The $key supplied to the add method should make sense in some context. The examples so
far have been fairly arbitrary, and are mainly designed to explain the concepts that are being
presented. However, MessageBag instances are most commonly encountered during validation
scenarios.
In cases like HTML form validation, the $key will generally be the name of the form element
being validated. Assuming the following HTML form element:
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $errors = new MessageBag;
5
6 // Add example error messages to the MessageBag instance.
7 $errors->add('username',
8 'The username field must longer than 5 characters');
9 $errors->add('username',
10 'The username field must contain a special character');
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add items to the MessageBag
7 $messageBag->add('first', 'First Message');
8 $messageBag->add('second', 'Second Message');
9 $messageBag->add('third', 'Third Message');
10 $messageBag->add('fourth', 'Fourth Message');
The following code will retrieve all of the messages with the given format:
After the above code has executed, the $messages variable will be an array and contain a value
similar to the following output:
1 array (size=4)
2 0 => string 'The message was: First Message' (length=30)
3 1 => string 'The message was: Second Message' (length=31)
4 2 => string 'The message was: Third Message' (length=30)
5 3 => string 'The message was: Fourth Message' (length=31)
11.1.3 any
The any method returns a boolean value indicating if the MessageBag instance actually has any
messages. The method returns true if the instance has messages, otherwise it returns false.
The following code examples demonstrate the usage of this fairly simple method:
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // false
7 $hasAny = $messageBag->any();
8
9 $messageBag->addMessage('first', 'The first message');
10
11 // true
12 $hasAny = $messageBag->any();
Message Bags 224
11.1.4 count
The count method returns the total number of messages stored within the MessageBag instance.
The count method exists to satisfy the requirements of PHP’s Countable¹ interface. The
following example shows the usage of the count method:
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add a few messages to the MessageBag instance.
7 $messageBag->add('first', 'This is a message');
8 $messageBag->add('first', 'I am also a message -.- ');
9 $messageBag->add('second', 'Can I join, too?');
10
11 // 3
12 $count = $messageBag->count();
It can be seen in the above example that the count message counts the number of messages
(which is 3), not necessarily the number of keys (which is 2).
1 use Illuminate\Support\MessageBag;
2
3
4 // Create a new MessageBag instance.
5 $messageBag = new MessageBag;
6 $messageBag->add('first', 'This is a message');
7 $messageBag->add('first', 'I am also a message -.- ');
8 $messageBag->add('second', 'Can I join, too?');
9
10 // 'This is a message'
¹http://php.net/manual/en/class.countable.php
Message Bags 225
11 $message = $messageBag->first();
12
13 // 'Can I join, too?'
14 $message = $messageBag->first('second');
15
16 // '' (an empty string)
17 $message = $messageBag->first('does_not_eixt');
The following example also changes the format of the returned message:
1 // <li>This is a message</li>
2 $message = $messageBag->first('first', '<li>:message</li>');
The following code will retrieve all of the messages with the given format:
After the above code has executed, the $messages variable will be an array and contain a value
similar to the following output. It can be seen that the output only contains the messages related
to the first key:
Message Bags 226
1 array (size=2)
2 0 => string 'The message was: The very first message' (length=39)
3 1 => string 'The message was: The second message' (length=35)
11.1.7 getFormat
The getFormat is the logical opposite of the setFormat method. It simply returns the current
format that is being used by the MessageBag instance.
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // :message
7 $format = $messageBag->getFormat();
8
9 // Change the format.
10 $messageBag->setFormat('<li>:message</li>');
11
12 // <li>:message</li>
13 $format = $messageBag->getFormat();
14
15 // Reset the format.
16 $messageBag->setFormat();
17
18 // :message
19 $format = $messageBag->getFormat();
11.1.8 getMessageBag
The getMessageBag method returns a reference to the MessageBag instance. It exists to satisfy
the requirements of the Illuminate\Contracts\Support\MessageProvider interface.
1 use Illuminate\Support\MessageBag;
2
3 // false
4 $isEqual = ($messageBag === $anotherMessageBag);
5
6 // true
7 $isEqual = ($messageBag === $messageBag->getMessageBag());
11.1.9 getMessages
The getMessages method is used to return all of the messages stored within the MessageBag
instance. The getMessages method will always return an array. If there are no messages in the
message bag, an empty array will be returned.
Message Bags 227
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add new messages to the message bag.
7 $messageBag->add('hello', 'The first message bag message');
8 $messageBag->add('world', 'The second message');
9
10 // Get an array of all the messages.
11 $messages = $messageBag->getMessages();
After the above code has executed, the $messages variable will be an array and contain a value
similar to the following output:
1 array (size=2)
2 'hello' =>
3 array (size=1)
4 0 => string 'The first message bag message' (length=29)
5 'world' =>
6 array (size=1)
7 0 => string 'The second message' (length=18)
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // false
7 $hasMessage = $messageBag->has('test');
8
9 // Add the message to the message bag.
10 $messageBag->add('test', 'Example message');
11
12 // true
13 $hasMessage = $messageBag->has('test');
Message Bags 228
11.1.11 isEmpty
The isEmpty method is the logical opposite of the any method. It returns a boolean value
indicating if the message bag is empty (having no messages). It returns true if the message
bag is empty; it returns false if the message bag contains messages.
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // true
7 $isEmpty = $messageBag->isEmpty();
8
9 $messageBag->addMessage('first', 'The first message');
10
11 // false
12 $isEmpty = $messageBag->isEmpty();
11.1.12 jsonSerialize
The jsonSeralize method internally returns the value of the toArray method. This method
exists to implement PHP’s JsonSerializable² interface, which allows developers to customize
how a class is represented when using the json_encode function.
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add new messages to the message bag.
7 $messageBag->add('hello', 'The first message bag message');
8 $messageBag->add('world', 'The second message');
9
10 // Get a value that can be converted to JSON.
11 $messages = $messageBag->jsonSerialize();
After the above code has executed, the $messages variable will be an array and contain a value
similar to the following output:
²http://php.net/manual/en/class.jsonserializable.php
Message Bags 229
1 array (size=2)
2 'hello' =>
3 array (size=1)
4 0 => string 'The first message bag message' (length=29)
5 'world' =>
6 array (size=1)
7 0 => string 'The second message' (length=18)
11.1.13 keys
The keys method is used to retrieve all of keys stored inside the MessageBag instance. The
following code example demonstrate the usage of the keys method:
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add items to the MessageBag
7 $messageBag->add('first', 'First Message');
8 $messageBag->add('second', 'Second Message');
9 $messageBag->add('third', 'Third Message');
10 $messageBag->add('fourth', 'Fourth Message');
11
12 // Get the MessageBag keys.
13 $keys = $messageBag->keys();
After the above code has executed, the $keys variable will be an array that contains a value
similar to the following output:
1 array (size=4)
2 0 => string 'first' (length=5)
3 1 => string 'second' (length=6)
4 2 => string 'third' (length=5)
5 3 => string 'fourth' (length=6)
It can be seen that the results contain only the keys that were added to the MessageBag instance.
11.1.14 merge($messages)
The merge method is used to combine, or merge, the contents of the MessageBag instance with
the provided $messages. The $messages can be any valid array or an object instance that
implements the Illuminate\Contracts\Support\MessageProvider interface. The merge
method modifies the original MessageBag instance and returns a reference to the instance.
For example, the array:
Message Bags 230
1 $arrayToMerge = [
2 'username' => [
3 'The username is required',
4 ],
5 'password' => [
6 'The passwords do not match',
7 ]
8 ];
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messages = new MessageBag;
5 $messages->add('username', 'That username has already been taken');
like so:
After the above code has executed, the $messageArray variable will be an array and contain a
value similar to the following output:
1 array (size=3)
2 0 => string 'That username has already been taken' (length=36)
3 1 => string 'The username is required' (length=24)
4 2 => string 'The passwords do not match' (length=26)
1 use Illuminate\Support\MessageBag;
2
3 // Create the first MessageBag instance.
4 $firstMessageBag = new MessageBag([
5 'username' => 'The username is required'
6 ]);
7
8 // Create the second MessageBag instance.
9 $secondMessageBag = new MessageBag([
10 'username' => 'That username has already been taken'
11 ]);
12
13 // Merge the two MessageBags.
14 $firstMessageBag->merge($secondMessageBag);
15
16 // Get the messages as an array.
17 $messageArray = $firstMessageBag->all();
After the above code has executed the $messageArray variable will be an array and contain a
value similar to the following output:
1 array (size=2)
2 0 => string 'The username is required' (length=24)
3 1 => string 'That username has already been taken' (length=36)
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // :message
7 $format = $messageBag->getFormat();
8
9 // Change the format.
10 $messageBag->setFormat('<li>:message</li>');
11
12 // <li>:message</li>
Message Bags 232
13 $format = $messageBag->getFormat();
14
15 // Reset the format.
16 $messageBag->setFormat();
17
18 // :message
19 $format = $messageBag->getFormat();
11.1.16 toArray
The toArray method can be used to retrieve the MessageBag instance as an array. It internally
accomplishes this by returning a call to the getMessages method.
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add new messages to the message bag.
7 $messageBag->add('hello', 'The first message bag message');
8 $messageBag->add('world', 'The second message');
9
10 // Get an array of all the messages.
11 $messages = $messageBag->toArray();
After the above code has executed, the $messages variable will be an array and contain a value
similar to the following output:
1 array (size=2)
2 'hello' =>
3 array (size=1)
4 0 => string 'The first message bag message' (length=29)
5 'world' =>
6 array (size=1)
7 0 => string 'The second message' (length=18)
11.1.17 toJson($options = 0)
The toJson method will return a JSON encoded version of the data stored within the message
bag instance. It internally does this by returning a call to PHP’s json_encode³ function, passing
in any $options that were supplied. Like the json_encode function, the $options parameter
is a bitmask of the predefined JSON constants⁴.
³http://php.net/manual/en/function.json-encode.php
⁴http://php.net/manual/en/json.constants.php
Message Bags 233
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag;
5
6 // Add items to the MessageBag
7 $messageBag->add('first', 'The very first message');
8 $messageBag->add('first', 'The second message');
9 $messageBag->add('second', 'I should not be in the output');
10
11 // Convert the MessageBag to JSON.
12 $jsonValue = $messageBag->toJson();
After the above code has executed, the $jsonValue variable would contain a value similar to
the following output (some lines have been wrapped and indented to improve readability):
After the above code has executed, the $jsonValue variable would now contain formatted JSON,
similar to the following output:
1 {
2 "first": [
3 "The very first message",
4 "The second message"
5 ],
6 "second": [
7 "I should not be in the output"
8 ]
9 }
The toJson method internally makes a call to PHP’s json_encode function. Unlike json_-
encode, toJson does not provide a way to specify the depth (essentially how many arrays are
nested inside of each other) to which data will be encoded, which is by default set to 512. To
convert a message bag instance into its JSON equivalent with a depth greater than 512, the
following method will be sufficient:
Message Bags 234
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag([]);
5
6 // Replace 512 with the desired depth.
7 $jsonValue = json_encode($messageBag->jsonSerialize(), 0, 512);
11.1.18 __toString
When a MessageBag instance is cast into a string, its JSON representation is returned as the
result. Internally this is accomplished by returning the result of the toJson method.
1 use Illuminate\Support\MessageBag;
2
3 // Create a new MessageBag instance.
4 $messageBag = new MessageBag([
5 'first' => ['The first message']
6 ]);
7
8 // Cast the MessageBag into a string.
9 $stringValue = (string) $messageBag;
After the above code executes, the $stringValue variable would contain the following value:
An instance of ViewErrorBag is shared with views if the current request contains any errors.
This functionality is facilitated by the Illuminate\View\Middleware\ShareErrorsFromSession
middleware. The ViewErrorBag instance that is shared with views is given the name errors.
Interacting with the ViewErrorBag instance should look familiar to most developers:
Message Bags 235
1 @if($errors->count())
2 <div class="alert alert-danger">
3 <p>There were some errors that need to be fixed!</p>
4 <ul>
5 {!! implode($errors->all('<li>:message</li>')) !!}
6 </ul>
7 </div>
8 @endif
The following examples will assume that a form exists that asks a user for their username and
a secret. The form will be validated from a controller using the following code sample (in this
case there is no response when validation was successful):
1 $this->validate($request, [
2 'username' => 'required|max:200',
3 'secret' => 'required'
4 ]);
If a user supplied only the username, the above Blade template code would generate the
following HTML:
If the user did not supply either a username or a secret, the following HTML code would have
been generated:
1 use Illuminate\Support\ViewErrorBag;
2
3 // Create a new ViewErrorBag instance.
4 $viewErrorBag = new ViewErrorBag;
5
6 // Determine if the default MessageBag
7 // instance is empty, which in this case
8 // is true.
9 $viewErrorBag->isEmpty();
11.2.1.1 count
The count method returns the number of messages stored within the default MessageBag
instance. It is also the only MessageBag method that specifically handled by the ViewErrorBag
instance itself because it needs to be declared within the ViewErrorBag class itself to satisfy the
requirements of PHP’s Countable⁵ interface.
The following code example demonstrates the behavior of the count method:
1 use Illuminate\Support\ViewErrorBag;
2 use Illuminate\Support\MessageBag;
3
4 // Create a new ViewErrorBag instance.
5 $viewErrorBag = new ViewErrorBag;
6
7 // Create a new MessageBag instance.
8 $messageBag = new MessageBag([
9 'username' => [
10 'The username is required.'
11 ]
12 ]);
13
14 // Add the new MessageBag instance to
15 // the ViewErrorBag
16 $viewErrorBag->put('formErrors', $messageBag);
17
18 // Get the count from $viewErrorBag
19 //
20 // 0
21 $messageCount = $viewErrorBag->count();
22
23 // Change the 'default' MessageBag to the one
24 // created earlier.
25 $viewErrorBag->put('default', $messageBag);
26
⁵http://php.net/manual/en/class.countable.php
Message Bags 237
As can be seen in the comments in the above example, the count method only operates on the
default MessageBag instance. Because of this adding the MessageBag formErrors did not
affect the count, but setting the same MessageBag instance as the value for the default key did
change the results of the count method.
The getBag method can be used to retrieve a MessageBag instance associated with the provided
$key. If a MessageBag instance does not exist with the provided $key, a new instance of
Illuminate\Support\MessageBag will returned instead.
The following code sample will demonstrate the usage of the getBag method. It also shows that
because of the way PHP internally handles objects and references, that the $messageBag is the
same as the value returned from the getBag method.
1 use Illuminate\Support\ViewErrorBag;
2 use Illuminate\Support\MessageBag;
3
4 // Create a new ViewErrorBag instance.
5 $viewErrorBag = new ViewErrorBag;
6
7 // Create a new MessageBag instance.
8 $messageBag = new MessageBag([
9 'username' => [
10 'The username is required.'
11 ]
12 ]);
13
14 $viewErrorBag->put('formErrors', $messageBag);
15
16 // Demonstrate that the object returned by the getBag
17 // method is the same as $messageBag.
18 //
19 // true
20 $areTheSame = $messageBag === $viewErrorBag->getBag('formErrors');
Additionally, you can request a MessageBag instance with any $key, even if they have not been
set:
Message Bags 238
It should be noted that the getBag method does not set the MessageBag instance that is
returning. This behavior can lead to some confusion, and can be observed in the following code
sample:
1 $messageBagInstance = $viewErrorBag->getBag('paymentErrors');
2
3 // Add a message to the $messageBagInstance
4 $messageBagInstance->add('ccn', 'The credit card number is invalid');
5
6 // Get the number of messages.
7 //
8 // 1
9 $messageCount = $messageBagInstance->count();
10
11 // Get the number of messages.
12 //
13 // 0
14 $messageCount = $viewErrorBag->getBag('paymentErrors')->count();
If the ViewErrorBag instance had set the MessageBag instance before returning it from the
getBag method, both $messageCount variables would have contained the value 1.
Another way to retrieve MessageBag instances from the ViewErrorBag instance is dynamically
access a property, where the property name is the intended key. This technique exhibits the same
behavior as using the getBag method.
11.2.1.3 getBags
The getBags method is used to return an associative array containing all the MessageBag
instances that are currently stored within the ViewErrorBag instance.
Message Bags 239
1 use Illuminate\Support\ViewErrorBag;
2 use Illuminate\Support\MessageBag;
3
4 // Create a new ViewErrorBag instance.
5 $viewErrorBag = new ViewErrorBag;
6
7 // Create a new MessageBag instance.
8 $messageBag = new MessageBag([
9 'username' => [
10 'The username is required.'
11 ]
12 ]);
13
14 // Add some message bags to $viewErrorBag
15 $viewErrorBag->put('formErrors', $messageBag);
16 $viewErrorBag->put('paymentErrors', new MessageBag);
17
18 // Get the message bags as an array.
19 $messageBags = $viewErrorBag->getBags();
After the above code has executed, the $messageBags variable would be an array and contain
a value similar to the following output:
1 array (size=2)
2 'formErrors' =>
3 object(Illuminate\Support\MessageBag)[142]
4 protected 'messages' =>
5 array (size=1)
6 'username' =>
7 array (size=1)
8 ...
9 protected 'format' => string ':message' (length=8)
10 'paymentErrors' =>
11 object(Illuminate\Support\MessageBag)[143]
12 protected 'messages' =>
13 array (size=0)
14 empty
15 protected 'format' => string ':message' (length=8)
The hasBag method is used to determine if a MessageBag instance exists within the ViewEr-
rorBag instance with the given $key. The $key is set to default unless it is changed. The
following example will highlight the usage of the hasBag method.
Message Bags 240
1 use Illuminate\Support\ViewErrorBag;
2 use Illuminate\Support\MessageBag;
3
4 // Create a new ViewErrorBag instance.
5 $viewErrorBag = new ViewErrorBag;
6
7 // Check if the 'default' MessageBag instance
8 // exists.
9 //
10 // false
11 $doesExist = $viewErrorBag->hasBag();
12 $doesExist = $viewErrorBag->hasBag('default');
13
14 // Check if a 'payments' MessageBag instance
15 // exists.
16 //
17 // false
18 $doesExist = $viewErrorBag->hasBag('payments');
19
20 // Add a new 'payments' MessageBag instance.
21 $viewErrorBag->put('payments', new MessageBag);
22
23 // Check again if the 'payments' MessageBag instance
24 // exists.
25 //
26 // true
27 $doesExist = $viewErrorBag->hasBag('payments');
The put method is used to add a new MessageBag implementation instance to the ViewEr-
rorBag instance, supplied as the argument to the $bag parameter with some name determined
by the $key argument. The following code demonstrates how to add a new MessageBag instance
to a ViewErrorBag:
1 use Illuminate\Support\ViewErrorBag;
2 use Illuminate\Support\MessageBag;
3
4 // Create a new ViewErrorBag instance.
5 $viewErrorBag = new ViewErrorBag;
6
7 // Create a new MessageBag instance.
8 $messageBag = new MessageBag;
9
10 // Add the $messageBag to the $viewErrorBag
11 // with some key.
Message Bags 241
12 $viewErrorBag->put('somekey', $messageBag);
13
14 // Get the number of MessageBag instances.
15 $messageBagCount = count($viewErrorBag->getBags());
After the above code has executed, the $messageBagCount variable would contain the value 1.
Another way to add MessageBag instances to the ViewErrorBag is by dynamically setting an
instance property:
At this point, the $viewErrorBag instance would now contain two MessageBag instances with
the keys somekey and anotherKey.
Because neither ViewErrorBag or MessageBag provide a method to quickly remove all the
messages from a MessageBag instance, the put method can be used to remove all MessageBag
messages, or supply new ones, by changing the MessageBag instance for a given key:
After the above code has executed, the $beforeChange variable will contain the old Message-
Bag instance and the $afterChange variable will contain the new MessageBag instance.
Message Bags 242
1 object(Illuminate\Support\MessageBag)[142]
2 protected 'messages' =>
3 array (size=0)
4 empty
5 protected 'format' => string ':message' (length=8)
1 object(Illuminate\Support\MessageBag)[143]
2 protected 'messages' =>
3 array (size=1)
4 'username' =>
5 array (size=1)
6 0 => string 'The username is required.' (length=25)
7 protected 'format' => string ':message' (length=8)
12. Fluent
The Illuminate\Support\Fluent class is a useful data type. It allows for the construction of a
data “container” similar to an array or instance of stdClass. However, the Fluent class makes
it easier to make assumptions about the data the class instance contains. The following array and
stdClass instance will be used for the next couple of examples:
The $value variable would now contain the value The first value. Similarly, data can be
retrieved from the stdClass instance using object operator (often called the “arrow”):
Like in the previous example, the $value variable would now contain the value The first
value. There is nothing surprising going on here. However, what happens when a developer
needs to make assumptions about the data their code is working with? Uncertain developers
often litter code with unwieldy if statements and similar constructs. Failure to do so generally
results in fatal errors.
For example, attempting to retrieve data from an array that does not exist results in an instance
of ErrorException being thrown:
243
Fluent 244
The exact error message will differ between single or multi-dimensional arrays, but the principal
is the same. PHP does not like it when code attempts to access array elements that do not exist.
The same can be said for accessing an object’s properties:
The above code example will again throw an instance of ErrorException, with the error
message being something similar to “Undefined property: stdClass::$doesNotExit”. To work
around this, the following code can be written:
The above code example can be simplified using Laravel’s array and object helper
functions. Specifically see the sections on array_get, object_get and data_get.
In the above code example, we checked to see if an object instance has a value by using the
property_exists function instead of the isset function. This is because the property_-
exist function will return true if the property exists and has a value of null. The isset
function will return false if the property exists but has a value of null.
http://php.net/manual/en/function.property-exists.php
Fluent 245
http://php.net/manual/en/function.isset.php
Developers need to assume things about code quite often. In a perfect world, developers would
know exactly what data an array or object their code interacts with contains. However, when
dealing with remote data, such as data from external APIs, or when interfacing with code from
multiple development teams, this is not always possible. The Fluent class can be used to simplify
things for developers.
The following example will create a new Fluent instance with some data:
Now that we have a Fluent instance, data can be retrieved just like an object or an array:
Both $value and $secondValue would contain the value The first value. Accessing data
that does not exist now simply returns null, without raising an error:
1 $value = $fluent['does_not_exist'];
2
3 $secondValue = $fluent->doesNotExist;
Both $value and $secondValue would contain the value null. The Fluent class does expose
public methods in its API to custom the default value returned.
The $default value is evaluated using the value helper function, meaning that it can be the
result of a function:
If we look at the following code example, one might be tempted to say that the value of $message
would be Hello, world!, but that would be incorrect:
Fluent 247
However, that would be incorrect. It is important to remember that the Fluent object is an
elaborate key/value storage container that can behave like an array or an object. When the fluent
container is created for an object containing a closure, such as the above example, the closure
instance is stored as the value. The following code will quickly prove this:
1 // true
2 $isClosure = ($fluent->method instanceof Closure):
To evaluate the closure and get the results, the value helper function can be used:
1 // Hello, world!
2 $message = value($fluent->method);
3
4 // Hello, world!
5 $message = value($fluent->get('method'));
12.1.2 getAttributes()
The getAttributes method simply returns an array containing all key/value pairs, representing
the underlying data contained within the Fluent instance.
After the following code is executed:
The $attributes variable would look have a value similar to the following:
Fluent 248
1 array (size=4)
2 'first' => string 'The first value' (length=15)
3 'second' => string 'The second value' (length=16)
4 'third' => string 'The third value' (length=15)
12.1.3 toArray()
The toArray method returns the exact same values as the getAttributes method.
12.1.4 jsonSerialize()
The jsonSerialize method internally returns a call to toArray. Because of this, toArray,
jsonSerialize and getAttributes are all functionally equivalent. The jsonSerialize
method exists to satisfy PHP’s JsonSerializable² interface, which allows developers to
customize how a class is represented when using the json_encode function.
12.1.5 toJson($options = 0)
The toJson method will return a JSON encoded version of the data stored within the fluent
instance. It internally does this by returning a call to PHP’s json_encode³ function, passing in
any $options that were supplied. Like the json_encode function, the $options parameter is
a bitmask of the predefined JSON constants⁴.
The following code:
would be converted into the following JSON, stored in the $jsonValue variable:
1 {
2 "first": "The first value",
3 "second": "The second value",
4 "third": "The third value",
5 "method": {}
6 }
The toJson method internally makes a call to PHP’s json_encode function. Unlike json_-
encode, toJson does not provide a way to specify the depth (essentially how many arrays are
nested inside of each other) to which data will be encoded, which is by default set to 512. To
convert a fluent object into its JSON equivalent with a depth greater than 512, the following
method will be sufficient:
1 namespace ExtensionExample
2 {
3 public static class StringExtension
4 {
5 public static int CountWords(this String str)
6 {
7 // Implementation of CountWords in C#
8 // return word count here.
9 }
10 }
11 }
Using Laravel’s macros a similar end-result can be accomplished. The following example will
add a countWords method to the Str support class:
1 use Illuminate\Support\Str;
2
3 Str::macro('countWords', function($value)
4 {
5 return str_word_count($value);
6 });
Class Description
Illuminate\Routing \ResponseFactory Responsible for creating responses that will be sent
back to the client.
Illuminate\Cache\Repository Handles interactions between the application and the
various cache stores.
Illuminate\Support\Str Contains string and text-manipulation related helper
functions.
250
Macros 251
Class Description
Illuminate\Filesystem\Filesystem Handles interactions between the application and the
file system.
Illuminate\Support\Arr Contains collection and array-manipulation related
helper functions.
Illuminate\Routing\Router Responsible for handling interactions with routes and
route-related activity.
1 use \Illuminate\Support\Str;
2
3 Str::macro('rot13', function($value)
4 {
5 return str_rot13($value);
6 });
After the rot13 macro has been defined, code can be written like the following:
1 $value = Str::rot13('test');
The Macroable trait’s internal mechanisms allow macros to be called from both static
and instance contexts.
Macros essentially become part of the class they are created for because of the internal
mechanisms that power them. Because of this, macro functions have access to all the private
and protected members of the class they are created for. With this knowledge, very powerful
macro functions can be created to add functionality to the framework that would otherwise be
difficult to accomplish.
The following code example highlights this fact by returning the $studlyCache member of the
\Illuminate\Support\Str class, which is declared to be protected static:
¹https://en.wikipedia.org/wiki/ROT13
Macros 252
1 Str::macro('getStudlyCache', function()
2 {
3 return self::$studlyCache;
4 });
5
6 // Call the 'studly' function a few times to make sure there
7 // are cache entries.
8 Str::studly('This is a test');
9 Str::studly('This is another test');
10
11 $cacheEntries = Str::getStudlyCache();
After the above code executes, the $cacheEntries variable would have the value:
1 array:2 [
2 "This is a test" => "ThisIsATest"
3 "This is another test" => "ThisIsAnotherTest"
4 ]
Trying to access the $studlyCache member directly would throw an instance of Sym-
fony\Component\Debug \Exception\FatalErrorExcepption with the following message:
hasMacro($macro)
The hasMacro method is used to determine if a given class has a macro with the name
$macro defined. It returns true if the $macro is found, otherwise it returns false.
__call($method, $parameters)
The Macroable trait implements PHP’s magic __call² method to intercept calls to
methods when in object context that do not exist in the current class. If a macro with
the given method name is found, it is evaluated and the result returned. If no macro is
found with the given name, an instance of BadMethodCallException is thrown.
²http://php.net/manual/en/language.oop5.overloading.php#object.call
Macros 253
__callStatic($method, $parameters)
The Macroable trait implements PHP’s magic __callStatic³ method to intercept calls
to a methods when in static context that do not exist on the target class. If a macro with
the given method name is found, it is evaluated and the result returned. If no macro is
found with the given name, an instance of BadMethodCallException is thrown.
1 use Illuminate\Support\Macroable;
2
3 class ExampleClass
4 {
5 use Macroable {
6 // Because this class also defines a '__call' method, a new
7 // name has to be given to the trait's '__call' method. The
8 // new name in this case is 'macroCall'.
9 __call as macroCall;
10 }
11
12 public function __call($method, $parameters)
13 {
14 // This will first check if a macro exists, and if it does
15 // the '__call' function will return the value of the
16 // 'macroCall' function (which is defined in the 'Macroable')
17 // trait.
18 if (static::hasMacro($method))
19 {
20 return $this->macroCall($method, $parameters);
21 }
22
23 // If no macro exists, continue with class-specific
24 // implementation of '__call'.
25 }
26
27 }
The above example is actually utilized within the framework itself with the implementation of
\Illuminate\Cache\Repository.
³http://php.net/manual/en/language.oop5.overloading.php#object.callstatic
Macros 254
The following table will list every framework class that implements the __call method directly.
The table will also indicate if the class supports macros even though it implements __call. Please
note that the following table does not take into account classes that implement the __callSatic
method (such as the Illuminate\Support\Facades\Facade class).
Class Macroable?
Illuminate\Foundation\Support No
\Providers\RouteServiceProvider
Illuminate\Support\ViewErrorBag No
Illuminate\Redis\Database No
Illuminate\Support\Manager No
Illuminate\Support\Fluent No
Illuminate\Cache\Repository Yes
Illuminate\Broadcasting \BroadcastManager No
Illuminate\Filesystem \FilesystemManager No
Illuminate\Http\RedirectResponse No
Illuminate\Queue\Capsule\Manager No
Illuminate\Routing\Controller No
Illuminate\Support \ServiceProvider No
Illuminate\Queue\QueueManager No
Illuminate\Pagination \AbstractPaginator No
Illuminate\Filesystem \FilesystemAdapter No
Illuminate\Cache\CacheManager No
Illuminate\Database \DatabaseManager No
Illuminate\Database \Eloquent\Relations\Relation No
Illuminate\Mail\Message No
Illuminate\View\View No
Illuminate\Database\Eloquent \Builder Yes See “Notes on Eloquent Builder”
Illuminate\Validation\Validator No
Illuminate\Database\Query \Builder No
Illuminate\Database\Eloquent \Model No
getMacro($name)
Returns the $callback (see macro($name Closure $callback) method) registered to
the macro with the given $name.
The Builder class handles determining if macros exist internally and does not expose any public
API for determining if a macro exists. This does not mean, however, that it cannot be determined
Macros 255
if a macro exists for the Builder. Because the getMacro internally makes a call to the array_-
get helper function without specifying a value for $default, the getMacro function will return
null if no matching macro is found.
14. Facades
Facades are a convenient way to access Laravel’s components. Each facade is bound to some
component already registered in the service container. Facades are typically used to provide a
simpler interface to an complex underlying subsystem. While some facades provide “shortcut”
methods, most of Laravel’s facades act like proxies by providing a static interface to an actual
class instance.
All of the default facades are located within the Illuminate\Support\Facades namespace
and can be located within the vendor/laravel/framework/src/Illuminate/Support/Fa-
cades directory. Every facade extends the abstract Facade (Illuminate\Support\Facades\Facade)
class and must provide a getFacadeAccessor() method which is defined to be protected.
The getFacadeAccessor() method indicates what class or component should be resolved from
the service container when the facade is accessed. All method calls are then redirected to that
class instance¹. Laravel refers to this class instance as the facade root.
Facade roots are the class instance that is bound in the service container. For example, the Auth
facade redirects all method calls to an instance of Illuminate\Auth\AuthManager, which the
service container resolves with the auth binding.
256
Facades 257
The alternative² is to inject the cache repository directly into the controller:
²Dependency injection is not the only alternative to using facades, it is, however, arguably the most common in Laravel projects.
Facades 258
Both code examples would accomplish the same thing: retrieve some_cache_item from the
cache storage. The facade example allows for shorter code, and code that is definitely easier to
follow along with. The second example has its own advantages too, which will not be covered
in this section.
1 <?php
2
3 class Calculator {
4
5 /**
6 * Adds two numbers.
7
8 * @param mixed $firstNumber
9 * @param mixed $secondNumber
10 * @return mixed
11 */
12 public function add($firstNumber, $secondNumber)
13 {
14 return $firstNumber + $secondNumber;
15 }
16
17 // Possibly many more methods.
18
19 }
The next thing that needs to happen is the class needs to be registered with the service container:
1 App::singleton('math', function()
2 {
3 return new Calculator;
4 });
Components are typically registered with the service container through the use of
Service Providers.
The Calculator class instance was bound as a singleton because there does not need to possibly
hundreds of instances of Calculator created: many consumers of the class can share a single
instance (note that not all classes should be bound as a singleton). The important part is that we
have an service container binding: math which will resolve to an instance of Calculator.
It is at this point a facade can be created. A facade is created by creating a new class and extending
Laravel’s abstract Facade class:
Facades 260
1 <?php
2
3 use Illuminate\Support\Facades\Facade;
4
5 class Math extends Facade {
6
7 /**
8 * Get the registered name of the component.
9 *
10 * @return string
11 */
12 protected static function getFacadeAccessor() { return 'math'; }
13
14 }
It is important to note that the value returned by the getFacadeAccessor() function matches
the name of the service container binding: math. The facade will use that value to request a class
instance from the service container and redirect method calls to that instance.
We will now examine how we would have used the Calculator class without the facade:
Examining the above code sample, it can be deduced that to add a new facade alias we simply
need to add a new entry to the aliases array. The key of the entry will become the name of the
alias and the value of the entry will become the class being aliased. To make this clearer, in the
above list Response is aliasing Illuminate\Support\Facades\Response, and both classes
can be used interchangeably.
We will use our Math facade from earlier, and we will assume it was defined in the Our\Applications
\Namespace. We could create an alias like so:
Developers can manually create an instance of the BladeCompiler themselves like so (this
Facades 265
1 <?php
2
3 use Illuminate\Support\Facades\App;
4
5 $bladeCompiler = App::make('view')->getEngineResolver()
6 ->resolve('blade')->getCompiler();
14.4.3.1 has($key)
The has function will check if a cookie with the given $key exists for the current request.
The get function will retrieve a cookie from the current request with the given $key. A
$default value can be supplied and will be returned if a cookie with the given $key does
not exist.
The get method will get an item from the input data, such as when a user posts a form or an API
request is being processed. The get method can be used for requests with the following HTTP
verbs:
• GET
• POST
• PUT
Facades 266
• DELETE
The get method will invoke the input method on an instance of the
Illuminate\Http\Request class.
The get method looks up the data based on the given $key. A $default value can be supplied
and will be returned if the given $key is not found in the request data.
14.4.5.1 connection($name)
In the above code example, the $className variable would contain the value Illumi-
nate\Auth \AuthManager.
This method of determining a facade’s underlying class can be expanded on to create a function
that will list every facade’s underlying class for the current Laravel installation:
³http://php.net/manual/en/function.get-class.php
Facades 267
1 /**
2 * Generates an HTML table containing all registered
3 * facades and the underlying class instances.
4 *
5 * @return string
6 */
7 function getFacadeReferenceTable()
8 {
9 $html = '';
10
11 // An array of all the facades that should be printed in the table.
12 $facades = [
13 'App', 'Artisan', 'Auth', 'Blade', 'Bus',
14 'Cache', 'Config', 'Cookie', 'Crypt', 'DB',
15 'Event', 'File', 'Hash', 'Input', 'Lang', 'Log',
16 'Mail', 'Password', 'Queue', 'Redis', 'Redirect',
17 'Request', 'Response', 'Route', 'Schema', 'Session',
18 'Storage', 'URL', 'Validator', 'View'
19 ];
20
21 // Boilerplate HTML to open an HTML table.
22 $html = '<table><thead><tr><th>Facade</th>';
23 $html .= '<th>Underlying Class</th></tr><tbody>';
24
25 foreach ($facades as $facade)
26 {
27 $html .= '<tr><td>',$facade,'</td><td>';
28 $html .= get_class(call_user_func($facade.'::getFacadeRoot'));
29 $html .= '</td></tr>';
30 }
31
32 // Boilerplate HTML to close an HTML table.
33 $html .= '</tbody></table>';
34
35 return $html;
36 }