Sei sulla pagina 1di 278

Laravel Companion

A Guide to Helpers, Collections And More

Johnathon Koster
This book is for sale at http://leanpub.com/laravelcompanion

This version was published on 2016-08-25

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.

© 2016 Johnathon Koster


Contents

Who is This Book For? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i


Symbols Used In This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
What Was Used to Write This Book? . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

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

1.30 trans($id = null, $parameters = [], $domain = 'messages', $lo-


cale = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.31 trans_choice($id, $number, array $parameters = [], $domain =
'messages', $locale = null) . . . . . . . . . . . . . . . . . . . . . . . . 26
1.32 e($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

2. Array Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29


2.1 Immutable Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.2 “Dot” Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3 add($array, $key, $value) . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.4 build($array, callable $callback) . . . . . . . . . . . . . . . . . . . . 31
2.5 divide($array) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.6 collapse($array) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.7 dot($array, $prepend = '') . . . . . . . . . . . . . . . . . . . . . . . . 36
2.8 except($array, $keys) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.9 only($array, $keys) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.10 flatten($array) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.11 fetch($array, $key) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.12 first($array, callable $callback = null, $default = null) . . . 43
2.13 last($array, callable $callback = null, $default = null) . . . 45
2.14 has($array, $key) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.15 set(&$array, $key, $value) . . . . . . . . . . . . . . . . . . . . . . . . 47
2.16 forget(&$array, $keys) . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
2.17 get($array, $key, $default = null) . . . . . . . . . . . . . . . . . . . 50
2.18 pull(&$array, $key, $default = null) . . . . . . . . . . . . . . . . . 51
2.19 pluck($array, $value, $key = null) . . . . . . . . . . . . . . . . . . . 52
2.20 where($array, callable $callback) . . . . . . . . . . . . . . . . . . . . 57
2.21 sort($array, callable $callback) . . . . . . . . . . . . . . . . . . . . 60
2.22 isAssoc(array $array) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
2.23 accessible($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
2.24 exists($array, $key) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
2.25 prepend($array, $value, $key = null) . . . . . . . . . . . . . . . . . 66

3. Application and User Flow Helper Functions . . . . . . . . . . . . . . . . . . . . . 68


3.1 app($make = null, $parameters = []) . . . . . . . . . . . . . . . . . . 68
3.2 auth($guard = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
3.3 policy($class) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.4 app_path($path = '') . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.5 base_path($path = '') . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.6 config_path($path = '') . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.7 database_path($path = '') . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.8 public_path($path = '') . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.9 storage_path($path = '') . . . . . . . . . . . . . . . . . . . . . . . . . . 72
3.10 abort($code, $message = '', array $headers = []) . . . . . . . . . 72
3.11 abort_if($boolean, $code, $message = '', array $headers) . . . 73
3.12 abort_unless($boolean, $code, $message = '', array $headers) 73
CONTENTS

3.13 Comparing abort, abort_if and abort_unless . . . . . . . . . . . . . . . 74


3.14 redirect($to = null, $status = 302, $headers = [], $secure =
null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
3.15 back($status = 302, $headers = []) . . . . . . . . . . . . . . . . . . . 77
3.16 response($content = '', $status = 200, array $headers = []) . 79
3.17 request($key = null, $default = null) . . . . . . . . . . . . . . . . . 80
3.18 view($view = null, $data = [], $mergeData = []) . . . . . . . . . . 81
3.19 old($key = null, $default = null) . . . . . . . . . . . . . . . . . . . . 82
3.20 event($event, $payload = [], $halt = false) . . . . . . . . . . . . 83
3.21 dispatch($command) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.22 factory() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.23 method_field($method) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.24 validator(array $data = [], array $rules = [], array $messages
= [], array $customAttributes = []) . . . . . . . . . . . . . . . . . . 86

4. Configuration, Environment, Security and Logging Helper Functions . . . . . . . 87


4.1 bcrypt($value, $options = []) . . . . . . . . . . . . . . . . . . . . . . 87
4.2 encrypt($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
4.3 decrypt($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.4 csrf_field() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.5 csrf_token() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
4.6 session($key = null, $default = null) . . . . . . . . . . . . . . . . . 91
4.7 cookie($name = null, $value = null, $minutes = 0, $path = null,
$domain = null, $secure = false, $httpOnly = true) . . . . . . . 92
4.8 config($key = null, $default = null) . . . . . . . . . . . . . . . . . 94
4.9 env($key, $default = null) . . . . . . . . . . . . . . . . . . . . . . . . 95
4.10 logger($message = null, $context = []) . . . . . . . . . . . . . . . . 97
4.11 info($message, $context = []) . . . . . . . . . . . . . . . . . . . . . . 97

5. URL Generation Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . .


99 .
5.1 action($name, $parameters = [], $absolute = true) . . . . . . .
99 .
5.2 asset($path, $secure = null) . . . . . . . . . . . . . . . . . . . . . .
100 .
5.3 secure_asset($path) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
100 .
5.4 url($path = null, $parameters = [], $secure = null) . . . . . .
101 .
5.5 secure_url($path, $parameters = []) . . . . . . . . . . . . . . . . .
102 .
5.6 elixir($file, $buildDirectory = 'build') . . . . . . . . . . . . . .
103 .
5.7 route($name, $parameters = [], $absolute = true, $route = null) 104

6. Miscellaneous Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106


6.1 dd() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
6.2 data_get($target, $key, $default = null) . . . . . . . . . . . . . . . 106
6.3 data_set(&$target, $key, $value, $overwrite = true) . . . . . . . 106
6.4 data_fill(&$target, $key, $value) . . . . . . . . . . . . . . . . . . . . 109
6.5 object_get($object, $key, $default = null) . . . . . . . . . . . . . 109
6.6 trait_uses_recursive($trait) . . . . . . . . . . . . . . . . . . . . . . . 110
6.7 value($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
6.8 with($object) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
CONTENTS

6.9 windows_os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112


6.10 tap($value, $callback) . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

7. Overriding the Default Helper Functions . . . . . . . . . . . . . . . . . . . . . . . 120

II Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

8. Basic Usage - Collections as Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 122


8.1 Notes on Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.2 Creating a New Collection Instance . . . . . . . . . . . . . . . . . . . . . . . 124

9. Collections: The Public API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126


9.1 all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
9.2 toArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
9.3 chunk($size, $preserveKeys = false) . . . . . . . . . . . . . . . . . . 128
9.4 collapse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
9.5 contains($key, $value = null) . . . . . . . . . . . . . . . . . . . . . . 132
9.6 count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.7 diff($items) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.8 diffKeys($items) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
9.9 each(callable $callback) . . . . . . . . . . . . . . . . . . . . . . . . . . 137
9.10 filter(callable $callback = null) . . . . . . . . . . . . . . . . . . . . 139
9.11 first(callable $callback = null, $default = null) . . . . . . . . 140
9.12 flatten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
9.13 flip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
9.14 forPage($page, $perPage) . . . . . . . . . . . . . . . . . . . . . . . . . . 143
9.15 forget($key) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9.16 get($key, $default = null) . . . . . . . . . . . . . . . . . . . . . . . . 145
9.17 groupBy($groupBy, $preserveKeys = false) . . . . . . . . . . . . . . . 146
9.18 has($key) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
9.19 implode($value, $glue = null) . . . . . . . . . . . . . . . . . . . . . . 152
9.20 intersect($items) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
9.21 isEmpty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
9.22 jsonSerialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
9.23 keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
9.24 last(callable $callback = null, $default = null) . . . . . . . . . 156
9.25 lists($value, $key = null) . . . . . . . . . . . . . . . . . . . . . . . . 158
9.26 map(callable $callback) . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
9.27 max($key = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
9.28 merge($items) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
9.29 min($key = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
9.30 pluck($value, $key = null) . . . . . . . . . . . . . . . . . . . . . . . . 163
9.31 pop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
9.32 prepend($value, $key = null) . . . . . . . . . . . . . . . . . . . . . . . 165
9.33 pull($key, $default = null) . . . . . . . . . . . . . . . . . . . . . . . . 166
9.34 push($value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
CONTENTS

9.35 put($key, $value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


167 .
9.36 random($amount = 1) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
168 .
9.37 reduce(callable $callback, $initial = null) . . . . . . . . . . .
169 .
9.38 reject($callback) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
170 .
9.39 reverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
171 .
9.40 search($value, $strict = false) . . . . . . . . . . . . . . . . . . . .
172 .
9.41 shift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
173 .
9.42 shuffle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
173 .
9.43 slice($offset, $length = null, $preserveKeys = false) . . . .
174 .
9.44 sort(callable $callback = null) . . . . . . . . . . . . . . . . . . . .
176 .
9.45 sortBy($callback, $options = SORT_REGULAR, $descending = false) 179
9.46 sortByDesc($callback, $options = SORT_REGULAR) . . . . . . . . . . 187
9.47 splice($offset, $length = null, $replacement = []) . . . . . . . 187
9.48 avg($key = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
9.49 average($key = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
9.50 sum($callback = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
9.51 take($limit) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
9.52 toJson($options = 0) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
9.53 __toString() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
9.54 transform(callable $callback) . . . . . . . . . . . . . . . . . . . . . . 198
9.55 unique($key = null) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
9.56 values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
9.57 where($key, $operator, $value = null) . . . . . . . . . . . . . . . . . 202
9.58 whereLoose($key, $value) . . . . . . . . . . . . . . . . . . . . . . . . . . 204
9.59 zip($items) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
9.60 combine($values) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
9.61 every($step, $offset = 0) . . . . . . . . . . . . . . . . . . . . . . . . . 209
9.62 except($keys) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
9.63 only($keys) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
9.64 keyBy($keyBy) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
9.65 whereIn($key, array $values, $strict = true) . . . . . . . . . . . . 215
9.66 whereInLoose($key, array $values) . . . . . . . . . . . . . . . . . . . . 216

10. Collections: The Static API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218


10.1 make($items = []) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218

III Additional Helper Classes and Features . . . . . 219


11. Message Bags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
11.1 Illuminate\Contracts\Support\MessageProvider Interface . . . . . . . 220
11.2 View Error Bags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

12. Fluent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243


12.1 Fluent Public API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

13. Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250


CONTENTS

13.1 Default Classes That Support Macros . . . . . . . . . . . . . . . . . . . . . . 250


13.2 Creating a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
13.3 Macroable Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

14. Facades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256


14.1 Facade Aliases and Importing Facades . . . . . . . . . . . . . . . . . . . . . . 256
14.2 Using Facades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
14.3 Creating Facades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
14.4 Facade Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
14.5 Resolving the Class Behind a Facade . . . . . . . . . . . . . . . . . . . . . . . 266
CONTENTS i

Who is This Book For?


This book is for anyone who uses the Laravel framework and would like to learn more about the
frameworks helper functions, Collection class, as well as many other helper features provided
by the framework.

Symbols Used In This Book

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.

This icon is used to provide additional contextually-relevant information to help clarify


ideas or to point out multiple ways of doing something.
CONTENTS ii

What Was Used to Write This Book?


The book publication and rendering was done using Leanpub (https://leanpub.com/¹). The book
was written using a custom variant of LeanPub’s markdown that is more suited for writing
large programming books (with specific tooling for writing about Laravel). The actual writing
took place in Adobe Brackets (http://brackets.io/²) using custom markdown and spell checking
plugins (the spell checking plugin is available for free on GitHub³).

¹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.1 Immutable Strings


Laravel’s string helper functions treat string values as immutable. This means that any given
string passed as a function argument will be unchanged, and a new, modified copy of the string
will be returned from the function (unless stated otherwise).

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):

• Any number of spaces ‘ ‘


• The underscore _
• The hyphen -

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.

1.5 snake($value, $delimiter = '_')


The snake helper method replaces all uppercase letters within the string with the lowercased
variant prefixed with the given $delimiter. The only exception to this rule is that if the first
character of the string is capitalized, it will be replaced by the lowercased variant without the
$delimiter being prefixed. Because of this behavior, the entire string will be lowercased. The
snake method trims extraneous whitespace from any string being converted:

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.5.1 snake_case($value, $delimiter = '_')


The snake_case function is a shortcut to calling Str::snake. This function is declared in the
global namespace.
String Helper Functions 6

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.

1.7 slug($title, $separator = '-')


The slug helper method will format the given $title to resemble a URI slug. It does this through
a series of steps:

• Convert the $title to ASCII formatting (using the ascii function);


• Converts whitespace, dashes, underscores to the $separator;
• Reduces whitespace and separators to a single character, and trims the whitespace and
separators from the beginning and end of the string.

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.7.1 str_slug($title, $separator = '_')


The str_slug function is a shortcut to calling Str::slug. This function is declared in the global
namespace.

1.8 contains($haystack, $needles)


The contains helper method will check if any of the $needles are in the given $haystack. If
any of the given $needles are found in the $haystack, the method will return true, otherwise
it returns false. $needles can be any value that can be converted into an array, and the
$haystack is any value that can be converted to a string. The case of the $haystack and
$needles is also important.

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.8.1 str_contains($haystack, $needles)


The str_contains function is a shortcut to calling Str::contains. This function is declared
in the global namespace.

1.9 endsWith($haystack, $needles)


The endsWith is used to check if a given $haystack ends with any of the supplied $needles.
The $haystack is any value that can be cast into a string, and $needles is any value that can be
cast into an array. If the $haystack ends with any of the $needles, the method returns true.
Otherwise, it returns false.

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.9.1 ends_with($haystack, $needles)


The ends_with function is a shortcut to calling Str::endsWith. This function is declared in
the global namespace.
⁵http://php.net/manual/en/function.range.php
String Helper Functions 9

1.10 startsWith($haystack, $needles)


startsWith does the opposite of ends_with, and has the same rules of use. Instead of checking
if a given $haystack ends with any of the supplied $needles, startsWith checks if a given
$haystack starts with any of the $needles.

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.10.1 starts_with($haystack, $needles)


The starts_with function is a shortcut to calling Str::startsWith. This function is declared
in the global namespace.

1.11 finish($value, $cap)


The finish helper method will make sure that a given $value always ends with exactly one
occurrence of the $cap. This helper method is incredibly useful when construction URIs or file
paths. The $cap can be any string of characters, and does not have to be only a single character.

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.', '.');

Combine this method with slug to create interesting results:


String Helper Functions 10

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.11.1 str_finish($value, $cap)


The str_finish function is a shortcut to calling Str::finish. This function is declared in the
global namespace.

1.12 is($pattern, $value)


The is helper method will indicate if the given $value matches the given $pattern. If the
$value is the $pattern or if the $value matches the $pattern, the method will return true,
otherwise it returns false.
The following examples will return true:

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

However, any of these would return true:

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.12.1 str_is($pattern, $value)


The str_is function is a shortcut to calling Str::is. This function is declared in the global
namespace.

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.14 limit($value, $limit = 100, $end = '...')


The limit method will make sure that the $value is never longer than the given limit. If it
is, the length is reduced and the specified end is added as a suffix. This method is useful when
displaying output from a user that could be very long and potentially cause issues with user
interface layouts. If the exact output length is important, it is possible that the final length is the
sum of the $limit and the length of the $end sequence.
String Helper Functions 12

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.14.1 str_limit($value, $limit = 100, $end = '...')


The str_limit function is a shortcut to calling Str::limit. This function is declared in the
global namespace.

1.15 words($value, $words = 100, $end = '...')


The words helper method is similar to the limit function, but instead of limiting the number
of characters returned, it limits the number of words returned.

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

1.18 plural($value, $count = 2)


The plural helper method will attempt to return a plural version of the given $value. It does
this through a series of specialized internal functions, that will not be covered in great detail here.
This helper method will apply general rules to strings ending in common character sequences,
handle special cases and will not attempt some very specific strings. The change in a word, such
as to show tense, or the number of items, is called an inflection.

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

Assuming the following messages array:

1 // The user's messages.


2 $messages = [
3 'You have a meeting on Saturday.',
4 'Your inbox is 90% full',
5 'Do not eat yellow snow'
6 ];

We could display the number of messages to the user like so:

⁶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:

1 You have 1 unread message.

Since the $messages array has 3 items in it, the user would see this:

1 You have 3 unread messages.

1.18.1 plural Special Cases


Any words, or word endings, in the following table will not be affected by the plural method.
This is either because the resulting word is already plural, or because there is no inflection
available. Word endings are denoted by the prefix *:

Words not Inflected

Amoyese Borghese Congoese Faroese Foochowese


Genevese Genoese Gilbertese Hottentotese Kiplingese
Kongoese Lucchese Maltese Nankingese Niasese
Pekingese Piedmontese Pistoiese Portuguese Sarawakese
Shavese Vermontese Wenchowese Yengeese *deer
*fish *lese *measles *media *mese
*nese *ois *pox *rese *sheep
audio bison bream breeches britches
buffalo cantus carp chassis clippers
cod coitus compensation contretemps cookie
coreopsis corps data debris diabetes
djinn education eland elk equipment
flounder gallows gold graffiti headquarters
herpes hijinks information innings jackanapes
mackerel mews money moose mumps
news nexus offspring people pincers
plankton pliers proceedings rabies rhinoceros
rice salmon scissors sea bass sea-bass
series shears siemens species staff
swine testes traffic trousers trout
tuna whiting wildebeest knowledge love
rain nutrition pokemon police series
String Helper Functions 15

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:

plural Special Cases

Singular Form Plural Form


atlas atlases
beef beefs
brother brothers
cafe cafes
child children
cookie cookies
corpus corpuses
cow cows
criterion criteria
ganglion ganglions
genie genies
genus genera
graffito graffiti
hoof hoofs
human humans
loaf loaves
man men
money monies
mongoose mongooses
move moves
mythos mythoi
niche niches
numen numina
occiput occiputs
octopus octopuses
opus opuses
ox oxen
penis penises
person people
sex sexes
soliloquy soliloquies
testis testes
trilby trilbys
turf turfs

1.18.2 str_plural($value, $count = 2)


The str_plural function is a shortcut to calling Str::plural. This function is declared in the
global namespace.
String Helper Functions 16

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

1.20 singular Special Cases


Any words, or word endings, in the following table will not be affected by the singular method.
This is either because the resulting word is already singular, or because there is no inflection
available. Word endings are denoted by the prefix *:

Words not Inflected

Amoyese Borghese Congoese Faroese Foochowese


Genevese Genoese Gilbertese Hottentotese Kiplingese
Kongoese Lucchese Maltese Nankingese Niasese
Pekingese Piedmontese Pistoiese Portuguese Sarawakese
Shavese Vermontese Wenchowese Yengeese *deer
*fish *lese *measles *media *mese
*nese *ois *pox *rese *sheep
*ss bison bream breeches britches
buffalo cantus carp chassis clippers
cod coitus contretemps corps debris
diabetes djinn eland elk equipment
flounder gallows graffiti headquarters herpes
hijinks information innings jackanapes mackerel
mews moose mumps news nexus
pincers pliers proceedings rabies rhinoceros
rice salmon scissors sea bass sea-bass
series shears siemens species staff
swine testes trousers trout tuna
String Helper Functions 17

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:

singluar Special Cases

Plural Form Singular Form


atlases atlas
beefs beef
brothers brother
cafes cafe
children child
cookies cookie
corpuses corpus
cows cow
criteria criterion
curves curve
foes foe
ganglions ganglion
genies genie
genera genus
graffiti graffito
hoofs hoof
humans human
loaves loaf
men man
monies money
mongooses mongoose
moves move
mythoi mythos
niches niche
numina numen
occiputs occiput
octopuses octopus
opuses opus
oxen ox
penises penis
people person
sexes sex
soliloquies soliloquy
testes testis
trilbys trilby
turfs turf
waves wave
String Helper Functions 18

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.

1.21 random($length = 16)


The random helper method generates a random string of the specified $length. This method
internally uses the OpenSSL function openssl_random_pseudo_bytes⁷, and therefore requires
the OpenSSL extension to be installed and configured⁸.

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:

Characters Removed by random

/ + =

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

1.21.1 str_random($length = 16)


The str_random function is a shortcut to calling Str::random. This function is declared in the
global namespace.
⁷http://php.net/manual/en/function.openssl-random-pseudo-bytes.php
⁸http://php.net/manual/en/openssl.installation.php
⁹http://php.net/manual/en/class.runtimeexception.php
String Helper Functions 19

1.22 quickRandom($length = 16)


The quickRandom helper method is similar to random in that it generates a random string to a
given $length. The quickRandom helper method does not rely on the OpenSSL extension, and
generates its random strings from a pool of alpha-numeric characters.

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.

The following examples show quickRandom sample output:

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.23 randomBytes($length = 16)


The randomBytes helper method is used to generate a string of bytes of the given $length.
The results of the randomBytes are more random than the results of the random method.
randomBytes requires the OpenSSL extension extension for PHP version 5 as it will internally
use the openssl_random_pseudo_bytes function. For PHP version 7, the random_bytes
function will be utilized. And as of Laravel version 5.2, the randomBytes helper method has
been deprecated in favor of PHP’s random_bytes function.
This method will throw an instance of RuntimeException if OpenSSL is not installed and
configured or if it was unable to generate a random string.

1.24 equals($knownString, $userInput)


The equals method will determine if two strings are the same. The equals method implements
a constant-time algorithm, meaning that the time it takes the method to complete does not
necessarily increase as the size of the two inputs ($knownString and $userInput) increases.
The method returns a boolean value, true if the strings are determined to be equal to one another
or false if the strings are determined to not be equal to one another.
The following examples will highlight some example usage of the equals method. The returned
result of the method will appear above the method call as a comment:
String Helper Functions 20

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.

1.24.1 Security Considerations


The equals method has the possibility of leaking length information about the given inputs
if the supplied $knownString and $userInput are of different lengths using timing attacks.
This is generally not a major issue, as preventing the leakage of length information is extremely
difficult, if not impossible. The equals method does not leak information about the differences
between the two strings.
For more information regarding this topic, refer to the following pages and articles:

• 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.25 parseCallback($callback, $default)


parseCallback is a fairly simple method, even though it serves a somewhat specialized purpose.
The following syntax for class names and method names can be found utilized throughout the
Laravel framework:
¹⁰http://php.net/manual/en/function.hash-equals.php
¹¹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
String Helper Functions 21

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

The return value would be:

1 array(2) {
2 [0] "MyClass"
3 [1] "defaultValue"
4 }

1 use Illuminate\Support\Str;
2
3 Str::parseCallback('MyClass@method', 'defaultValue');

The return value would be:

1 array(2) {
2 [0] "MyClass"
3 [1] "method"
4 }

1 use Illuminate\Support\Str;
2
3 Str::parseCallback('MyClass@method@somethingElse', 'defaultValue');

The return value would be:


String Helper Functions 22

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('', '');

The return value would be:

1 array(2) {
2 [0] ""
3 [1] ""
4 }

An example use of this function could look like this:

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.26 replaceFirst($search, $replace, $subject)


The replaceFirst helper method is used to replace the first occurrence of a given $search
string with the provided $replace string in the $subject string. All three parameters are
required and must be strings.
The following examples highlight the basic usage of the replaceFirst method. The results of
the method call will appear above the call as a comment.

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.26.1 str_replace_first($search, $replace, $subject)


The str_replace_first function is a shortcut to calling Str::replaceFirst. This function
is declared in the global namespace.

1.27 replaceLast($search, $replace, $subject)


The replaceLast helper method is the logical opposite of the replaceFirst helper method.
It is used to replace the last occurrence of a given $search string with the provided $replace
string in the $subject string. ALl three parameters are required and must be strings.
The following examples highlight the basic usage of the replaceLast method. The results of
the method call will appear above the call as a comment.

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

1.27.1 str_replace_last($search, $replace, $subject)


The str_replace_last function is a shortcut to calling Str::replaceLast. This function is
declared in the global namespace.

1.28 substr($string, $start, $length = null)


The substr helper method is a convenient helper built on top of PHP’s mb_substr¹⁵ function
(unlike PHP’s mb_substr function, substr does not provide a way to change the encoding that
is used) that is used to return a portion of a string. The substr method defines two required
parameters ($string and $start) and one optional parameter ($length).
An argument supplied for $string must be the string that you want to return a portion of.
$start is used to determine where the substring starts (all positions start at 0). If the $start is
positive, the substring will start at the supplied position from the start of the string. If $start is
negative, the substring will start at the supplied position from the end of the string. The $length
is used to determine how the long the returned substring will be (in other words, how many
characters are allowed in the returned substring). If $length is null, the substring will continue
on to the end of the string.

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.'), '.');

1.30 trans($id = null, $parameters = [], $domain =


'messages', $locale = null)

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.

1 // The :attribute must be an array.


2 trans('validation.array');
3
4 // The provided value must be an array.
5 trans('validation.array', ['attribute' => 'provided value']);

It should be noted that the placeholder name in the $parameters parameter should not contain
the leading : character.

1.31 trans_choice($id, $number, array $parameters =


[], $domain = 'messages', $locale = null)

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:

1 // There is one book.


2 trans_choice('plural.books', 1);

The following code example would select the second message:

1 // There are 4 books.


2 trans_choice('plural.books', 4, ['choice' => 4]);

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 // There are 4 books.


2 trans_choice('plural.books', 4, ['choice' => 4]);
3
4 // There is one book.
5 trans_choice('plural.books', 1, ['choice' => 1]);

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 $unsafeClientCode = '<script>alert("hello everyone");</script>';


2
3 $safeClientCode = e($unsafeClientCode);

The value of $safeClientCode would then be:

1 &lt;script&gt;alert(&quot;hello everyone&quot;);&lt;/script&gt;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.

2.1 Immutable Arrays


All of the array helper functions below, unless stated otherwise, treat arrays as an immutable
data structure. This means that any changes made to an array are returned as a copy of the
original array, with the original array remaining unchanged.
Here is a quick example:

1 use Illuminate\Support\Arr;
2
3 $originalArray = [
4 'fruit' => 'orange',
5 'vegetable' => 'carrot'
6 ];
7
8 $anotherArray = array_add($originalArray, 'vehicle', 'car');

Executing var_dump on $originalArray would produce the following output:

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 }

2.2 “Dot” Notation


In addition to treating arrays as immutable, Laravel’s functions support “dot” notation when
accessing items in an array. This is similar to JavaScript’s dot notation when accessing object
properties.
JavaScript:

1 forms = document.forms;

PHP, using Laravel’s helper functions:

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.

2.3 add($array, $key, $value)


The add helper method adds the given $key and $value to an $array if the $key doesn’t
already exist within the given $array.
Consider the following code snippet:
Array Helper Functions 31

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

The the end result would be:

1 array(3) {
2 ["animal"] "Araripe Manakin"
3 ["plant"] "Pineland Wild Petunia"
4 ["insect"] "Extatosoma Tiaratum"
5 }

2.3.1 array_add($array, $key, $value)


The array_add function is a shortcut to calling Arr::add. This function is declared in the global
namespace.

2.4 build($array, callable $callback)


The $build helper method will create a new array with the original array’s key/value pairs after
they have been run through the $callback function. The $callback function should return an
array with the new key and value.
The following code sample will append is rare to the values in the original array:

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

The final array would be:


Array Helper Functions 32

1 array(2) {
2 ["animal"] "Araripe Manakin is rare"
3 ["plant"] "Pineland Wild Petunia is rare"
4 }

2.4.1 array_build($array, callable $callback)


The array_build function is a shortcut to calling Arr::build. This function is declared in the
global namespace.

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

The final result would be:

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

The value of $collapsedArray would then be:

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

The value of $collapsedArray would then have the value:

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

2.6.1 Collapsing Collections


The collapse method will also work on collections. There is no special syntax required to use
collections with the collapse method:
Array Helper Functions 35

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

The value of $collapsedArray would then be:

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

Nested collections can also be collapsed:

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

The value of collapsed array would then be:


Array Helper Functions 36

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.

2.7 dot($array, $prepend = '')


The dot helper method will take a multi-dimensional array and return a new associative array
where the keys are built from all the nested keys, separated with the . character.

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

The final array would look like this:

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 $myArray = Arr::dot($myArray, 'prepended_');

Would have produced the following array instead:

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 }

2.7.1 array_dot($array, $prepend = '')


The array_dot function is a shortcut to calling Arr::dot. This function is declared in the global
namespace.

2.8 except($array, $keys)


The except helper method will return all the key/value pairs of the $array where the keys in
the original array are not in the $keys array.
Assuming that the $_POST super-global contains the following information:

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

$inputData would then contain the following items:

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.

Passing an array would look like this:


Array Helper Functions 38

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']);

2.8.1 array_except($array, $keys)


The array_except function is a shortcut to calling Arr::except. This function is declared in
the global namespace.

2.9 only($array, $keys)


The only helper method is the logical opposite of the except method. Using the same $_POST
array from the previous example, we could retrieve only a user’s first name like so:

1 use Illuminate\Support\Arr;
2
3 $inputData = Arr::only($_POST, 'first_name');

With the resulting array looking like this:

1 array(1) {
2 ["first_name"] "John"
3 }

2.9.1 array_only($array, $keys)


The array_only function is a shortcut to calling Arr::only. This function is declared in the
global namespace.

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 ];

If we flatten the array like so:

1 $newArray = Arr::flatten($arrayToFlatten);

the resulting array would be:

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.

2.11 fetch($array, $key)

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 ];

we could fetch the names of all the courses like so:

1 use Illuminate\Support\Arr;
2
3 $courses = Arr::fetch($students, 'courses');

which return the following array:


Array Helper Functions 41

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

which would return this array:

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

which would return the following result:


Array Helper Functions 42

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 }

Retrieving a Unique List of Languages


To quickly retrieve a list of all the unique languages all students speak, we can first flatten the
array using the flatten method:

1 $languages = Arr::flatten($languages);

which would create the following array:

1 array(4) {
2 [0] "French"
3 [1] "English"
4 [2] "Spanish"
5 [3] "English"
6 }

At this point PHP’s array_unique can be used:

1 $languages = array_unique($languages);

which would return the following array:

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

2.11.1 array_fetch($array, $key)


The array_fetch function is a shortcut to calling Arr::fetch. This function is declared in the
global namespace. This helper function was removed in Laravel 5.1.

2.12 first($array, callable $callback = null,


$default = null)

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

and this would return false:

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

The above code would return /post/this-is-my-default-value when no key/value pair


satisfies the callback function.

2.12.1 Optional $callback Parameter


The $callback function is an optional parameter, and can be omitted. When the $callback
parameter is omitted, the first method will return the first item in the array:
Array Helper Functions 45

1 use Illuminate\Support\Arr;
2
3 // 'browser'
4 $firstItem = Arr::first($sampleArray);

2.12.2 array_first($array, $callback, $default = null)


The array_first function is a shortcut to calling Arr::first. This function is declared in the
global namespace.

2.13 last($array, callable $callback = null,


$default = null)

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

the value of $lastPost would be:


/post/last-post

2.13.1 Optional $callback Parameter


The $callback function is an optional parameter, and can be omitted. When the $callback
parameter is omitted, the last method will return the last item in the array:
Array Helper Functions 46

1 use Illuminate\Support\Arr;
2
3 // 'something else'
4 $firstItem = Arr::last($sampleArray);

2.13.2 array_last($array, $callback, $default = null)


The array_last function is a shortcut to calling Arr::last. This function is declared in the
global namespace.

2.14 has($array, $key)


The has helper method will return a boolean value that indicates if the given $key exists in the
supplied $array, using dot notation. This method is incredibly useful when checking if an array
has a specific key at an arbitrary depth.
Considering the following array:

1 $anArray = [
2 'nested_array_one' => [
3 'nested_array_two' => [
4 'key' => 'value'
5 ]
6 ]
7 ];

We can determine that the nested key actually does exist:

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

At this point, the value of $doesExist would be false, which is accurate.


Using this method is easier to read than using PHP’s isset function and checking at each level
of the array whether a particular key exists.
Array Helper Functions 47

2.14.1 array_has($array, $key)


The array_has function is a shortcut to calling Arr::has. This function is declared in the global
namespace.

2.15 set(&$array, $key, $value)


The set helper method is the logical opposite of the forget method. It’s purpose is to set values
within an array.

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

Which would produce a familiar looking array:

1 array(1) {
2 ["person"] array(2) {
3 ["first_name"] "Jane"
4 ["last_name"] "Doe"
5 }
6 }

Overwriting the value of first_name is also easy to accomplish:

1 Arr::set($testArray, 'person.first_name', 'John');

The $testArray would now look like this:


Array Helper Functions 48

1 array(1) {
2 ["person"] array(2) {
3 ["first_name"] "John"
4 ["last_name"] "Doe"
5 }
6 }

2.15.1 Using set to change the entire array


The set function can be used to change the entire value of the array. This is accomplished by
passing null as the value for $key. When null is used for the $key, the $value will be assigned
to the $array variable. The effects of this can be observed below.
For the following examples, the following array definition will be used:

1 $testArray = [
2 'first' => 'element',
3 'second' => 'element'
4 ];

Replacing the $array with a new array


Given the following array:

1 $newArray = [
2 'third' => 'element',
3 'fourth' => 'element'
4 ];

We can reassign the arrays like so:

1 use Illuminate\Support\Arr;
2
3 Arr::set($testArray, null, $newArray);

The value of $testArray would now be:

1 array(2) {
2 ["third"] "element"
3 ["fourth"] "element"
4 }

Replacing the $array with a completely different type


Since the set function will give the $array whatever the $value is when the $key is null, the
original type of the variable can be changed completely.
For example, setting the $array to null:
Array Helper Functions 49

1 use Illuminate\Support\Arr;
2
3 $testArray = Arr::set($testArray, null, null);

Setting the $array to 100:

1 use Illuminate\Support\Arr;
2
3 $testArray = Arr::set($testArray, null, 100);

2.15.2 array_set(&$array, $key, $value)


The array_set function is a shortcut to calling Arr::set. This function is declared in the global
namespace.

2.16 forget(&$array, $keys)


The forget helper method removes items from the given $array. The specified keys are express
in dot notation.

Mutable Function
This function affects the original $array.

Assuming an array is defined as follows:

1 use Illuminate\Support\Arr;
2
3 $anArray = [
4 'person' => [
5 'first_name' => 'Jane',
6 'last_name' => 'Doe'
7 ]
8 ];

We could remove the first_name value like so:

1 Arr::($anArray, 'person.first_name');

Which would leave the array as follows:


Array Helper Functions 50

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 Arr::forget($anArray, ['person.first_name', 'person.last_name']);

2.16.1 array_forget(&$array, $keys)


The array_forget function is a shortcut to calling Arr::forget. This function is declared in
the global namespace.

2.17 get($array, $key, $default = null)


The get helper method will retrieve an item from the given $array using dot notation. This
allows developers to retrieve items from the array at arbitrary depths quickly, without having to
use PHP’s array syntax.
Assuming the following array:

1 $anArray = [
2 'nested_array_one' => [
3 'nested_array_two' => [
4 'key' => 'value'
5 ]
6 ]
7 ];

We can quickly retrieve the value for key like so:

1 use Illuminate\Support\Arr;
2
3 $value = Arr::get($anArray, 'nested_array_one.nested_array_two.key');

Where the alternative syntax would be:

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.

2.17.1 array_get($array, $key, $default = null)


The array_get function is a shortcut to calling Arr::get. This function is declared in the global
namespace.

2.18 pull(&$array, $key, $default = null)


The pull helper method is similar to the get method in that it will return a value for the
given $key in the $array (or the $default, if it is specified and the $key does not exists).
The difference is that the pull method will remove the item it finds from the array.

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

The $weekDays array would now look like this:

1 array(6) {
2 [1] "Sunday"
3 [3] "Tuesday"
4 [4] "Wednesday"
5 [5] "Thursday"
6 [6] "Friday"
7 [7] "Saturday"
8 }

2.18.1 array_pull(&$array, $key, $default = null)


The array_pull function is a shortcut to calling Arr::pull. This function is declared in the
global namespace.

2.19 pluck($array, $value, $key = null)


The pluck helper method is used to retrieve a list of specific values from a given $array. It is
most useful when used against arrays of objects, but will also work with arrays just as well. Let’s
use the following class to describe a person:

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 }

We can create an array of people like so:


Array Helper Functions 53

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

The value of $lastNames would then look like this:

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

And just as before, the value of $lastNames would be:


Array Helper Functions 54

1 array(3) {
2 [0] "Carter"
3 [1] "Doe"
4 [2] "Smith"
5 }

2.19.1 Returning an array with a key/value pair


We can also instruct the pluck method to return an array that contains both a key and a value.
We do this by passing in a third argument to the pluck function: the $key.
Let’s reuse the people array:

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

The value of $peopleList would now look like this:

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

The value of $peopleList would now look like this:


Array Helper Functions 55

1 array(3) {
2 ["Carter"] "Jane"
3 ["Doe"] "John"
4 ["Smith"] "Jack"
5 }

2.19.2 Working with nested arrays or objects


The $key supports dot notation, which implies that we can search for keys at arbitrary depths
when constructing the final array. Let’s add a new Job class, which will just be a very simple
representation of a job:

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 }

The same techniques will also work on nested arrays.

2.19.3 array_pluck($array, $value, $key = null)


The array_pluck function is a shortcut to calling Arr::pluck. This function is declared in the
global namespace.

2.20 where($array, callable $callback)


The where helper method is functionally similar to the pluck method, in that both take a source
$array and filter it to produce a smaller array. It works by iterating over each element in the
$array and executing the $callback on each key value pair. If the $callback returns a value
that evaluates to true, the key/value pair is kept, otherwise it is ignored when constructing the
final array.
Comparing just the value
Assume we have an array of numbers, from 0 to 100:

1 $numbers = range(0, 100);

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

$smallNumbers would then look like this:


Array Helper Functions 58

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 }

Comparing both key and value


That example only used the $value from the array, the following example will make use of both
the key and value.
Consider the following array of students and test scores:

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

The value of $studentsWhoPassed would be:


Array Helper Functions 59

1 array(2) {
2 ["Alice"] 95
3 ["Allison"] 96
4 }

Comparing just the key


For completeness, let’s look at an example of just utilizing the key from the key/value compare
with the where method.
Let’s add another array to the mix to keep track of all the students that are currently suspended:

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

Anonymous functions and variable scope


In PHP, whenever the execution of the script enters into a function, the scope changes.
This is still true for Closures and anonymous functions. That is why the above example
is using the use keyword: to bring the $suspendedPeople variable from another scope
into the current scope.
It should be noted that when variables are “pulled into” the current scope, the current
scope receives a copy of that variable. That is why the call to array_flip does not
change the original array.

The value of $validTestScores would then be:


Array Helper Functions 60

1 array(4) {
2 ["Alice"] 95
3 ["Allison"] 96
4 ["Bob"] 92
5 ["Delbert"] 72
6 }

2.20.1 array_where($array, callable $callback)


The array_where function is a shortcut to calling Arr::where. This function is declared in the
global namespace.

2.21 sort($array, callable $callback)


The sort helper method will allow you to sort the given $array based on some condition
returned by the $callback. The method works by iterating over all the values in the $array
and passing the values it finds into the $callback function. It then uses the value returned by
the callback to determine sort order.
Let’s refactor our students example to use a class based structure. First, we will create a new
StudentTestResult class:

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 }

At this point we can build a new $testScores array:


Array Helper Functions 61

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 ];

Now, the $testScores array will look like this:

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

The $sortedScores array will now look like this:

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 }

Alternatively, we can sort the array based on the student’s name:


Array Helper Functions 63

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

And now the $sortedScores array would look like this:

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 }

Array Sort Considerations


The array_sort function internally creates a new instance of the \Illuminate\Support\Collection
class with the given $array and then calls the collection’s sortBy(callable $callback =
null) method with the given $callback. It then converts the sorted collection into an array
by calling the collection’s all() method. In short, this function creates a new object every
time it is invoked. Because of this function’s internal behavior, code should never be written
like the following:
Array Helper Functions 64

1 // Create a new collection, using the 'Collect' helper.


2 $collection = collect(['second', 'first', 'third']);
3 $sorted = array_sort($collection->all());

Instead, it is preferable to just use the collection’s sortBy method directly:

1 $collection = collect(['second', 'first', 'third']);


2 $sorted = $collection->sortBy();

2.21.1 array_sort($array, callable $callback)


The array_sort function is a shortcut to calling Arr::sort. This function is declared in the
global namespace.

2.22 isAssoc(array $array)


The isAssoc helper method can be used to determine if a given $array is an associative array
or not. The provided documentation for the isAssoc method states that an array is associative
if it does not have sequential numeric keys beginning with zero. However, in practice the actual
results are slightly more nuanced:

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:

1 // Create some test objects to work with.


2 $array = [];
3 $collection = collect([]);
4 $model = factory('App\User')->make();
5 $class = new stdClass;
6
7 // true
8 Arr::accessible($array);
9
10 // true
11 Arr::accessible($collection);
12
13 // true
14 Arr::accessible($model);
15
16 // false
17 Arr::accessible($class);
18
19 // false
20 Arr::accessible(null);

2.24 exists($array, $key)


The exists helper method is similar to PHP’s array_key_exists² function in that in can be
used to check if the given $key or index exists with the provided $array. The exists method
defines two parameters, and both are required.

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

2.25 prepend($array, $value, $key = null)


The prepend helper method is used to push a new $value onto the beginning of an existing
$array. It defines one optional parameter: $key. If an argument is supplied for $key, the new
item will be given that key. Supply a value for $key if you want to control the new items key
when adding a new item to an associative array. This method does not affect the original array,
and returns a new, modified, copy of the original array.
The following examples demonstrate the usage of the prepend helper method:
Array Helper Functions 67

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 ]

2.25.1 array_prepend($array, $value, $key = null)


The array_prepend helper function is a shortcut to calling the Arr::prepend helper method.
This function is declared in the global namespace.
3. Application and User Flow Helper
Functions
3.1 app($make = null, $parameters = [])
The app function provides access to the Illuminate\Container\Container instance. Because
Container is a singleton, any call to app() will return the same Container instance.

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:

1 // $authManager will be an instance of


2 // Illuminate\Auth\AuthManager
3 $authManager = app('auth');

3.2 auth($guard = null)


Used without supplying any arguments for $guard, the auth helper function is an alterna-
tive to using the Auth facade. With no arguments, the auth function returns an instance
of Illuminate\Contracts\Auth\Factory (which by default is an instance of Illumi-
nate\Auth\AuthManager).

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:

1 // Not passing anything for `$guard`.


2 if (auth()->attempt([
3 'email' => $email,
4 'password' => $password
5 ])) {
6
7 }
8
9 // Passing the default configuration value for `$guard`.
10 if (auth('web')->attempt([
11 'email' => $email,
12 'password' => $password
13 ])) {
14
15 }

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.

3.4 app_path($path = '')


The app_path will return the full path to the Laravel application directory (which is named app
by default). The exact value returned by calling app_path is dependent on the specific folder
structure where the application is residing. An example path returned might look like this:

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/'), '/');

3.5 base_path($path = '')


The base_path function can be used to retrieve the path to the directory the Laravel application
is installed in. It can also be used to construct paths relative to the base path by supplying a $path.
The following examples will assume that the Laravel application is installed in the
/home/vagrant/Code/Laravel/ directory. The resulting path will appear above the function
calls as a comment.

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'), '/');

3.6 config_path($path = '')


The config_path function can be used to retrieve the path the config directory. It can also be
used to construct paths relative to the configuration directory by supplying a $path.
The following examples will assume that the Laravel application is installed in the
/home/vagrant/Code/Laravel/ directory. The resulting path will appear above the function
calls as a comment.

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

3.7 database_path($path = '')


The database_path function can be used to retrieve the path to the database directory. It can
also be used to construct paths relative to the database directory by supplying a $path.
The following examples will assume that the Laravel application is installed in the
/home/vagrant/Code/Laravel/ directory. The resulting path will appear above the function
calls as a comment.

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'), '/'):

3.8 public_path($path = '')


The public_path will return the path to the public directory. It can also be used to construct
paths relative to the public directory if a $path is supplied.
The following examples will assume that the Laravel application is installed in the
/home/vagrant/Code/Laravel/ directory. The resulting path will appear above the function
calls as a comment.
Application and User Flow Helper Functions 72

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'), '/');

3.9 storage_path($path = '')


The storage_path will return the path to the storage directory. It can also be used to construct
paths relative to the storage directory if a $path is supplied.
The following examples will assume that the Laravel application is installed in the
/home/vagrant/Code/Laravel/ directory. The resulting path will appear above the function
calls as a comment.

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'), '/');

3.10 abort($code, $message = '', array $headers =


[])

The abort function will throw an instance of


Symfony\Component\HttpKernel\Exception\HttpException with the given $code, $mes-
sage and any $headers supplied. These exceptions can be caught and handled through the
application’s kernel.
Application and User Flow Helper Functions 73

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 }

3.11 abort_if($boolean, $code, $message = '', array


$headers)

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.

1 // These two function calls are equivalent.


2 abort_if(!$user->admin);
3 abort_if(($user->admin == false));

3.12 abort_unless($boolean, $code, $message = '',


array $headers)

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

3.13 Comparing abort, abort_if and abort_unless


All three functions (abort, abort_if and abort_unless) can cause the execution of an
application to stop. Each of them can cause the exact same end result, but the abort_if and
abort_unless functions allow for the writing of code that reads easier and takes up less space.
The following examples will all accomplish the same task to show the subtle differences in how
each function is used.
The following examples assume 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 // Check to make sure that the user is


2 // an administrator. If not, we will
3 // abort the execution of the app.
4
5 // Using the `abort` function.
6 if (!$user->admin) {
7 abort(401);
8 }
9
10 // Using the `abort_if` function.
11 abort_if(!$user->admin, 401);
12
13 // Using the `abort_unless` function.
14 abort_unless($user->admin, 401);

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

3.14 redirect($to = null, $status = 302, $headers =


[], $secure = null)

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.

3.14.1 Accessing the Redirector using redirect


The Redirector class has many useful methods to help control the flow of users in your
application. This section will not cover each method in detail, but simply shows how they can
be used in conjunction with the redirect helper function:
Application and User Flow Helper Functions 75

1 // Accessing `Redirector` methods using the `redirect` function:


2
3 return redirect()->back();
4 return redirect()->home();
5 return redirect()->to('/');

3.14.2 Redirecting to a Given Path


When an argument that is not null is supplied for the $to parameter, the redirect helper
function will internally make a call to the to method on the Redirector instance. The function
will also pass in all the arguments supplied to redirect as the arguments to its internal to
method call. The following lines are equivalent and would have the exact same effects:

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

We could redirect the users there using:

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

3.14.3 Redirecting to Secure URLs


A truth value of true can be supplied as an argument for the $secure parameter to generate
secure (HTTPS) URLs when redirecting:

1 return redirect('/', 302, [], true);

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

3.14.4 Redirecting to Custom URLs


The Redirector does not provide a direct way to add additional information when generated
the final URL, except for the $secure parameter. Luckily, the Redirect uses the Illumi-
nate\Routing\UrlGenerator when generating URLs. Specifically, it calls the to method
which will check to see if the path supplied is already a valid URL. This means that we can
supply or generate URLs to redirect to without having to worry about the URL being rewritten:

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

3.14.5 Changing the HTTP Status Code


To change the status code of the response simply supply an argument for the $status parameter:

1 // Redirect with a "301: Moved Permanently" status code.


2 return redirect('/', 301);
3
4 // Redirect with a "307: Temporary Redirect" status code.
5 return redirect('/', 307);

Appendix B: HTTP Status Codes contains a table of common HTTP status codes.

3.14.6 Supplying Additional Headers


In order to supply extra headers we must also provide an argument for $status and then supply
an argument for $headers:

1 // Redirect with a "302: Found" status code and extra headers:


2 return redirect('/', 302, [
3 'Cache-Control' => 'no-cache, must-revalidate'
4 ]);
Application and User Flow Helper Functions 77

3.15 back($status = 302, $headers = [])


The back helper function is used to create a redirect response to the user’s previous location.
It defines two parameters which can be used to control the status code and headers of the
response. An integer argument can be supplied for the $status parameter to change the HTTP
status code for the request. By default, the code is 302 (“Found”), but could easily be changed to
301 (“Moved Permanently”). Specific headers can also be set by providing an argument for the
$headers parameter. There is an example of this below. The back function returns an instance
of Illuminate\Http\RedirectResponse.
The following examples show different ways to return a RedirectResponse from a controller
action. The examples assume that some controller class exists with a method named postCre-
ateSomeValue. The actual details of the controller class and method are not important for these
examples.

3.15.1 Returning a Redirect Response Using the Redirect Facade


The Redirect facade resolves to an instance of Illuminate\Routing\Redirector, which is
where the back method is defined:

1 use Illuminate\Support\Facades\Redirect;
2
3 function postCreateSomeValue() {
4 // ... code here ...
5 return Redirect::back();
6 }

3.15.2 Returning a Redirect Response Using the response Helper


Function
Like the Redirect facade, the redirect helper function will resolve an instance of Illumi-
nate\Routing\Redirector from the service container and then all the back method that is
defined there:

1 function postCreateSomeValue() {
2 return redirect()->back();
3 }

3.15.3 Returning a redirect response using the back helper


function:
Application and User Flow Helper Functions 78

1 function postCreateSomeValue() {
2 // ... code here ...
3 return back();
4 }

3.15.4 Changing the HTTP Status Code


To change the status code of the response simply supply an argument for the $status parameter:

1 // Redirect back with a "301: Moved Permanently" status code.


2 return back(301);
3
4 // Redirect back with a "307: Temporary Redirect" status code.
5 return back(307);

Appendix B: HTTP Status Codes contains a table of common HTTP status codes.

3.15.5 Supplying Additional Headers


In order to supply extra headers we must also provide an argument for $status and thens supply
an argument for $headers:

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

3.16 response($content = '', $status = 200, array


$headers = [])

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:

1 return response()->make('I am the response content!');


2 return response('I am the response content!');

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.

3.16.1 Changing the HTTP Status Code


To change the status code of the response simply supply an argument for the $status parameter:

1 // Create a response with the `404` status code.


2 return response('That page was not found.', 404);

Appendix B: HTTP Status Codes contains a table of common HTTP status codes.

3.16.2 Supplying Additional Headers


In order to supply extra headers we must also provide an argument for $status and then supply
an argument for $headers:
Application and User Flow Helper Functions 80

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

3.17 request($key = null, $default = null)


The request helper function is a useful helper function that can be used to either retrieve an
instance of Illuminate\Http\Request or retrieve an item from the user’s input. To retrieve
an instance of Request, call the request method without supplying any arguments. To retrieve
an input value, supply at least the $key argument.
The following example demonstrates how to retrieve an instance of Request using the request
helper function:

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:

1 // Get client IP address.


2 request()->ip();
3
4 // Determine if request is secure.
5 if (request()->secure()) {
6 // Request is secure.
7 }
8
9 // Determine if request is the result
10 // of an AJAX call.
11 if (request()->ajax()) {
12 // Request is XMLHTTPRequest.
13 }

The following example demonstrates how to retrieve user input using instance methods. The
examples assume that name exists in the user input array.

1 // Get the user's name from input.


2 $name = request()->input('name');
3
4 // Get the user's name from input
5 // with a default value.
6 $name = request()->input('name', 'John Doe');

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

1 // Get the user's name from input.


2 $name = request()->input('name');
3 $name = request('name');
4
5 // Get the user's name from input
6 // with a default value.
7 $name = request()->input('name', 'John Doe');
8 $name = request('name', 'John Doe');

Using the request helper function, we can access only a subset of the user’s input data:

1 // Get only the user's name.


2 $name = request()->only('name');

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:

1 // Retrieve a subset of the user's input data.


2 $inputSubset = request([
3 'name',
4 'email'
5 ]);

3.18 view($view = null, $data = [], $mergeData =


[])

The view function can be used to return an implementation of Illuminate\Contracts\View\Factory


(by default this is an instance of Illuminate\View\Factory) or an implementation in-
stance of Illuminate\Contracts\View\View (which by default would be an instance of
Illuminate\View\View). The examples in this section will make use of the default wel-
come.blade.php example view file that ships with new Laravel installations.
If no arguments are supplied to the view helper function, the Factory implementation will be
returned and all available Factory methods will be available to you:

1 // Check to see if a view exists.


2 if (view()->exists('welcome')) {
3 // The welcome view exists.
4 }

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 // Create a new View instance with data.


2 $view = view('welcome', collect([
3 'name' => 'John Doe'
4 ]), ['version' => '1.0.0']);

But this will throw an instance of ErrorException:

1 // Create a new View instance with data.


2 $view = view('welcome', collect([
3 'name' => 'John Doe',
4 ]), collect([
5 'version' => '1.0.0'
6 ]));

3.18.1 Rendering a View to a String


Sometimes it is useful to store the rendered contents of a view as a string for further processing.
The following example demonstrates how to accomplish this using the view helper function:

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.

3.19 old($key = null, $default = null)


The old helper function is used to retrieve an old input item. It is a shortcut to calling
the Illuminate\Http\Request::old instance method. It accepts a $key argument and a
$default argument. They $key should be the name of the input item to retrieve and a $default
value can be supplied that will be returned if the given $key does not exist.
The following example demonstrates how to use the old helper function and assumes that an
input item with the key name exits:
Application and User Flow Helper Functions 83

1 // Retrieve the old name.


2 $userName = old('name');
3
4 // Retrieve the old name with
5 // a default value.
6 $userName = old('name', 'John Doe');

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

3.20 event($event, $payload = [], $halt = false)


The event helper is a convenient way to dispatch a particular $event to its listeners. An optional
$payload of data can also be supplied when dispatching the event. When the event is dispatched,
all it’s listeners will be called and any responses from the listener will be added to an array. The
array of responses is generally the return value of the event function.
If the $halt parameter is set to true, the dispatcher will stop calling listeners after any of the
listeners return a value that is not null. If no listeners have returned a response and all listeners
were called, the event function will return null.
The following examples will highlight the various ways to use the event function:

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 }

An event can be fired by the name of a class like so:

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:

1 $event = new VideoWasWatched($video);


2 event('App\Events\VideoWasWatched', $event);

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:

1 // Return an instance of the 'User' model.


2 $user = factory('App\User')->make();
3
4 // Return two instances of the 'User' model.
5 $users = factory('App\User', 2)->make();
6
7 // Return one instance of the 'User' model, with some modifications
8 // that were defined earlier and bound to the 'admin' description.
9 $adminUser = factory('App\User', 'admin')->make();
10
11 // Return two instances of the 'User' model, with some modifications
12 // that were defined earlier and bound to the 'admin' description.
13 $adminUsers = factory('App\User', 'admin', 2)->make();

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

1 <input type="hidden" name="_method" value="PUT">


2 <input type="hidden" name="_method" value="POST">
3 <input type="hidden" name="_method" value="GET">
4 <input type="hidden" name="_method" value="PATCH">
5 <input type="hidden" name="_method" value="DELETE">

3.24 validator(array $data = [], array $rules = [],


array $messages = [], array $customAttributes
= [])

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 for ($i = 0; $i < 10; $i++)


2 {
3 // echo the hash and an HTML line break
4 echo bcrypt('test'),'<br>';
5 }

The above example would output something similar to this:

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

4.1.1 bcrypt Options


The following table lists all of the options that are available to use in with the bcrypt function.

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.

1 // Compute a hash with a 'cost' of 4


2 bcrypt('test', ['rounds' => 4]);
3
4 // Compute a hash with a 'cost' of 5
5 bcrypt('test', ['rounds' => 4]);
6
7 // These will throw an `ErrorException`
8 bcrypt('test', ['rounds' => 3]);
9 bcrypt('test', ['founds' => 32]);

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>

can be simplified to just:

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>

or with Blade syntax:

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.

The following is an example of what the csrf_token function may output:


Configuration, Environment, Security and Logging Helper Functions 91

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>

4.6 session($key = null, $default = null)


The session function is a versatile function. It can be used to return the \Illuminate\Session
\SessionManager instance, to set session values and to retrieve session values.

4.6.1 Returning an instance of


\Illuminate\Session\SessionManager

To return an instance of the \Illuminate\Session\SessionManager class, set the $key


parameter to null. If the $key parameter is set to null, the $default parameter is completely
ignored.

1 // Get the SessionManager instance.


2 $sessionManager = session();

4.6.2 Setting a Session Value


The session function allows setting session values directly by passing in an array of key/value
pairs. The following example demonstrates this:
Configuration, Environment, Security and Logging Helper Functions 92

1 // Settings two session values 'test' and 'test'2


2 session([
3 'test' => 'A test message',
4 'test2' => 'Another test message'
5 ]);

Setting single session values is also possible:

1 // Setting a single session value.


2 session()->put('test3', 'Yet another test message');

4.6.3 Retrieving a Session Value


Values can be retrieved with the session function by supplying a $key. To retrieve the test
value from the earlier example the function call would look like so:

1 // Retrieving the 'test' value.


2 $value = session('test');

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:

1 // Retrieving a value that does not exist.


2 $valueThatDoesNotExist = session('does_not_exist', 'A default value');

In the above example the value of $valueThatDoesNotExit would be A default value.

4.7 cookie($name = null, $value = null, $minutes =


0, $path = null, $domain = null, $secure =
false, $httpOnly = true)

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.

Cookies and Responses


When using the cookie function to create a cookie, it is important to remember that
the function will not send the cookie to client. It will simply create the cookie and
return an instance of \Symfony\Component\HttpFoundation\Cookie.

The cookie function defines seven optional parameters:


Configuration, Environment, Security and Logging Helper Functions 93

$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

1 // Creating a cookie, with a basic value.


2 $cookie = cookie('test_basic', 'The cookie value');
3
4 // Creating a HTTPS-only cookie.
5 $cookie = cookie('test_secure', 'Value', null, null, null, true);

4.8 config($key = null, $default = null)


The config helper function is a versatile function. If the supplied $key and $default value are
both null, such as in the following method call:

1 // Calling the `config` function without any arguments


2 config();

the return value will be, by default, an instance of Illuminate\Config\Repository (more


specifically, the return value will be whatever class instance is bound to the config alias within
the service container). This can be used a shortcut to accessing the coniguration repository
(versus injecting an instance of the configuration repository or using the Config facade):

1 // Using the `config` function to return an instance of


2 // `Illuminate\Config\Repository` to check if a config item exists.
3 if (config()->has('someKey')) {
4 // Do something if the `someKey` config item exists.
5 }

4.8.1 Setting configuration values


The config function can be used to set configuration values if the provided $key is an array,
and no $default value is supplied (or the $default value supplied is null). If multiple items
are passed exist in the array, all key/value pairs will added to the configuration:

1 // New config items to store.


2 $newConfigurationValues = [
3 'keyOne' => 'valueOne',
4 'keyTwo' => 'valueTwo',
5 'keyThree' => 'valueThree'
6 ];
7
8 // Store all three key/value pairs in the config.
9 config($newConfigurationValues);

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

4.8.2 Retrieving configuration values


The config function can even be used to retrieve configuration values, as long as the provided
$key is not an array and not null. A $default value can be supplied that will be returned if
the configuration $key does not exist. The following examples will use the $newConfigura-
tionValues from the previous section. The value returned will appear above the function call
as a comment:

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

4.9 env($key, $default = null)


The env function can be used to get an environment variables value. If an environment value
with the given $key exists, it’s value will be returned. If the given $key does not exist, the
$default value will be returned instead, which is null by default. The following examples will
show examples of the env function.
The following examples will use the following .env file:
Configuration, Environment, Security and Logging Helper Functions 96

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

4.10 logger($message = null, $context = [])


The logger helper function is a versatile function. If the $message is null, which it is by default,
the logger function will return an implementation of Illuminate\Contracts\Logging\Log,
which by default is an instance of \Illuminate\Log\Writer class.
When the logger function is not being used to retrieve a Log instance, a $message can be set
and it will be written to Laravel’s log files. An optional $context can also be supplied. The
$context must be an array, although the actual elements of the array do not have to be arrays
themselves.
The following example shows the usage of the logger helper function when supplying a
$message and $context. An example of what the function calls would produce in the log files
follows the code examples.

1 // An example message context.


2 $context = ['name' => 'John Doe', 'email' => 'you@homestead'];
3
4 // A log message without context.
5 logger('This is a log message without context');
6
7 // A log message where the context is an array.
8 logger('This is a log message', $context);
9
10 // A log message where the context is an array of objects.
11 logger('This is another log message', [(object) $context]);

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 ...

4.11 info($message, $context = [])


The info helper will write an information entry into Laravel’s log files. It allows a $message to
be set, as well as an optional $context (which is an array of data). Whole the $context must
be an array, the actual elements of the array do not have to be arrays themselves.
The following example shows the usage of the info helper. An example of what the function
calls would produce in the log files follows the code examples.
Configuration, Environment, Security and Logging Helper Functions 98

1 // An example message context.


2 $context = ['name' => 'John Doe', 'email' => 'you@homestead'];
3
4 // A log message without context.
5 info('This is a log message without context');
6
7 // A log message where the context is an array.
8 info('This is a log message', $context);
9
10 // A log message where the context is an array of objects.
11 info('This is another log message', [(object) $context]);

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

Calling the action helper function like so:

1 action('ExampleController@sayHello', ['name' => 'Jim']);

would return the following URL:

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

5.1.1 Relative URLs


If you do want to generate the full URL to a controller action, simply supply a truth value of
false for the $absolute parameter. The following example demonstrates this:

1 action('ExampleController@sayHello', ['name' => 'Jim'], false)

The resulting URL of the function call would then be:

1 /sayHello/Jim

5.2 asset($path, $secure = null)


The asset function will return a URI composed of the application’s URI and the given $path. If
$secure is true, the returned URI will have the https:// schema, otherwise it will have the
http:// schema.

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

5.3.1 Notes on asset and secure_asset


If the supplied $path to asset and secure_asset contains a protocol, that protocol is used
regardless of what function or flags are set. For example, if a URI with the http:// protocol is
supplied to the secure_asset function, the resulting URI will contain the http:// protocol. In
addition, if a domain name is supplied to either of the functions, that domain name will be used
instead of the domain present in the request.

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

5.4 url($path = null, $parameters = [], $secure =


null)

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.

The following lines are equivalent:


URL Generation Helper Functions 102

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

both calls would result in the following URL:

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']);

would result in the following URL being generated:

1 http://laravel.artisan/arbitraryUrl/someParameter

5.4.1 Generating Secure URLs


To generate secure URLs using the url helper function, supply an argument with the truth value
of true to the $secure parameter. To generate secure URLs that do not require parameters
simply supply an empty array [] as the argument for $parameters.
The following examples demonstrate both ways of generating secure URLs:

1 url('arbitraryUrl', [], true)


2 url('arbitraryUrl', ['someParameter'], true)

1 https://laravel.artisan/arbitraryUrl
2 https://laravel.artisan/arbitraryUrl/someParameter

5.5 secure_url($path, $parameters = [])


The secure_url helper function can be used to generate secure, fully qualified URLs to a given
$path. You can also supply additional data that will be added as a query string by supplying an
argument for the $parameters parameter.

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 ])

The resulting URL would be similar to the following output:

1 https://laravel.artisan/arbitraryUrl/someParameter

5.6 elixir($file, $buildDirectory = 'build')


The elixir helper function can be used to get the path to a versioned Elixir file. The function
accepts two arguments, the name of the $file to find the path for and the $buildDirectory
to look in. By default, the $buildDirectory is set to build. The build directory is relative to
the applications public directory (app/public).
Assuming the following simple gulpfile:

1 var elixir = require('laravel-elixir');


2
3 elixir(function(mix) {
4 mix.sass('app.scss');
5
6 // Version using the default configured build path.
7 mix.version('css/app.css');
8
9 // Version using a custom build path.
10 mix.version('css/app.css', 'public/build2');
11 });

The path to the file versioned using the default configured build directory can be determined
like this:

1 elixir('css/app.css');

and would produce output similar to the following:


URL Generation Helper Functions 104

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

which would produce output similar to the following:

1 /build2/css/app-64f4edce94.css

5.7 route($name, $parameters = [], $absolute = true,


$route = null)

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 Route::get('user/profile', ['as' => 'profile', function () {


2 return 'User profile route.';
3 }]);

We can generate a simple URL to it using the following example:

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

The resulting URL would look something like this:

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:

1 // Fully qualified URL.


2 $urlOne = route('profile', [
3 'custom' => 'data'
4 ]);
5
6 // Relative URL.
7 $urlTwo = route('profile', [
8 'custom' => 'data'
9 ], false);

The resulting URLs would be:

1 Fully qualified URL.


2 http://laravel.artisan/user/profile?custom=data
3
4 Relative URL.
5 /user/profile?custom=data
6. Miscellaneous Helper Functions
6.1 dd()
The dd function is a debug utility that will dump a set of values and then die. This means it will
create a human-readable representation of the values and then stop execution of the script.
The dd function will take into account if the application is currently running in the console, or if
it is returning a response to a client (such as a browser), and then update it’s output accordingly.

6.2 data_get($target, $key, $default = null)


The data_get function is identical in behavior to both the array_get and object_get
function. The difference is that the data_get function will accept both objects and arrays as
it’s $target.

6.3 data_set(&$target, $key, $value, $overwrite =


true)

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 ]

6.3.1 Using data_set with Objects


There is no difference in using the data_set helper function with objects instead of arrays. The
following example demonstrates how we could use the data_set function fill a newly created
object. The example does not handle nested items.

1 // Create a test array to work with.


2 $testArray = [
3 'first_name' => 'Jane',
4 'last_name' => 'Doe',
5 'age' => 26
6 ];
7
8 // Create a test object to work with.
9 $testObject = new stdClass;
10
11 foreach ($testArray as $key => $value) {
12 data_set($testObject, $key, $value);
13 }

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 }

6.4 data_fill(&$target, $key, $value)


The data_fill helper function accomplishes the same fundamental task as the data_set
helper function. The only difference is that the data_fill does not define an optional
$overwrite parameter. data_fill internally makes a call to the data_set helper function
with $overwrite set to false. This function does not overwrite data.
The following function calls are equivalent wand would produce the same results:

1 // Create a object to work with.


2 $testObject = new stdClass;
3
4 // Set data using `data_fill`.
5 data_fill($testObject, 'name', 'Jane');
6
7 // Set data using `data_set`.
8 data_set($testObject, 'name', 'Jane', false);

6.5 object_get($object, $key, $default = null)


The object_get allows developers to retrieve properties from a given $object using dot
notation. This is useful in situations where it can not be guaranteed that a supplied object will
have a given property, represented by the $key.
The following sample class structure will be used in the following examples:

1 $sampleObject = new stdClass;


2 $sampleObject->department = new stdClass;
3
4 $sampleObject->department->name = 'Marketing';

The department name can be retrieved like so:

1 $departmentName = object_get($sampleObject, 'department.name');

The value of $departmentName would then be Marketing.


Attempting to retrieve the department’s address would return NULL:
Miscellaneous Helper Functions 110

1 // NULL
2 $departmentAddress = object_get($sampleObject, 'department.address');

Or a different $default value can be supplied:

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 }

The traits used by ExampleClass can be determined by:

1 $traits = trait_uses_recursive('ExampleClass');

The $traits variable would contain the following array:


Miscellaneous Helper Functions 111

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 $classInstance = new ExampleClass;


2
3 $traits = trait_uses_recursive($classInstance);

Again, the $traits variable would contain the following values:

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

Again, $value would contain the integer 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.

Alternative to the with Function


The same effect provided by the with function can be accomplished using vanilla PHP. The
technique is to wrap object instantiation within a pair of parenthesis (( and )):

1 $value = (new ExampleClass)->someMethod();

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 }

instead of code like this:

1 <?php
2
3 if (strtolower(substr(PHP_OS, 0, 3)) === 'win') {
4 // Windows&reg; specific commands or instructions.
5 } else {
6 // Anything that is not Windows&reg;.
7 }

6.10 tap($value, $callback)


The tap helper function is used to call a given Closure (provided as an argument to the
$callback parameter) with the given $value. The tap helper function will return the reference
to the original $value as its return value. This allows you to call any number of methods with
any type of return values within the $callback while maintaining a reference to the original
object. This behavior is particularly useful during method chaining. Another way to think of this
functions behavior is that it allows you to specify and fix the return value of a series of method
calls, regardless of what methods are called within the internal block.

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 }

Using the new helper function might look like this:

1 <?php
2
3 echo saySomething('Hello World');

The user would see the following text in the browser:

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 // ...

Tap Function Closure Arguments


In the previous example the Closure defines a parameter named $t. When the tap function
executes, the value of $talker will be used as the inner value of $t and they will refer to the
same Talker instance. The following diagram visually demonstrates the flow of data in the
tap helper function.
Miscellaneous Helper Functions 118

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

The Illuminate\Support\Collection class provides a wrapper around PHP’s arrays. The


Collection class has numerous methods for retrieving, setting and manipulating the data of
the underlying array. Each Collection instance has an internal array which is used to store the
actual collection items.
8. Basic Usage - Collections as Arrays
Because Laravel’s Collection class is an extravagant wrapper around PHP arrays, it’s basic
usage should be very familiar to most PHP developers. The Collection class also implements
PHP’s ArrayAccess¹ interface so that developers can use PHP’s array syntax when working
with collections:

1 // Creating a new collection instance.


2 $collection = new Collection;
3
4 // Appending to the collection.
5 $collection[] = 'First';
6 $collection[] = 'Second';
7 $collection[] = 'Third';
8
9 // Adding key/value pairs to the collection.
10 $collection['key'] = 'Some value';
11 $collection['key2'] = 'Some other value';
12
13 foreach ($collection as $key => $value) {
14 // Iterate through the array with access to key/value pairs.
15 }
16
17 // Retrieve the value associated with a known key.
18 $someValue = $collection['key'];

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)

8.1 Notes on Basic Usage


Any caveats that apply when working with arrays in PHP also apply to Collection instances
when treating them as arrays. This means that developers have to check for the existence of items
themselves when accessing or iterating over the collection. For example, the following code will
produce an ErrorException stating that the index does_not_exist does not exist:

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.

8.2 Creating a New Collection Instance


There are a few different ways to create a new Collection instance with existing data. The first
way to create a new instance is to pass an array of items to the Collection class’s constructor:

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

1 // An array of test data.


2 $testData = [
3 'first' => 'This is the first',
4 'second' => 'This is the second',
5 'third' => 'This is third'
6 ];
7
8 // Create a new collection instance using the 'collect' helper.
9 $collection = collect($testData);
9. Collections: The Public API
The Collection class exposes a generous public API, consisting of 64 public methods. The
Collection API exposes methods for retrieving values from a collection, transforming the
underlying array, pagination and simple aggregate functions, amongst others. This section will
cover most of the methods in the public API, excluding those methods required to implement
PHP’s ArrayAccess¹ and IteratorAggregate²interfaces, as well as the getCachingItera-
tor method.

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)

9.3 chunk($size, $preserveKeys = false)


The chunk method is useful when working with large collections in that it allows developers
to create smaller collections to work with. The chunk method defines two parameters: $size,
which is used to control how large each newly created collection will be; and $preserveKeys,
which indicates if the chunk method will preserve array keys when creating the new collections.
Assuming the following code:

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

The $chunks variable will contain a value similar to the following:


Collections: The Public API 129

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:

1 $chunks = $collection->chunk(3, true);

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)

The resulting collections now have the original array keys.


Collections: The Public API 130

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

The collapse method internally calls the Illuminate\Support\Arr::collapse($array)


helper function. It will collapse both nested arrays and Collection instances.

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

9.5 contains($key, $value = null)


The contains method is used to determine if a given $key exists within the collection.
Additionally, an option $value can be specified that will be used to check if a given key/value
pair exists within the collection. The contains method is incredibly versatile, and each use case
will be highlighted below.
The following demonstrates the contains method in its most basic usage:

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

9.5.1 Considerations of the contains method


The contains method defines two parameters: $key and $value. The $value parameter has a
default value of null, however, the two method calls are not the same:
Collections: The Public API 135

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.

The following examples will demonstrate the usage of the diff:


Collections: The Public API 136

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:

1 $firstCollection = collect(['name' => 'Shiny New Tablet', 'price' => 799.99]);


2 $secondCollection = collect(['name' => 'Shiny New Tablet', 'description' => '\
3 Much shinier and bigger!']);
4
5 $differences = $firstCollection->diffKeys($secondCollection);

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 $firstCollection = collect(['name' => 'Shiny New Tablet', 'price' => 799.99]);


2 $secondCollection = collect([
3 'name' => 'Shiny New Tablet',
4 'description' => 'Much shinier and bigger!'
5 ]);
6
7 $differences = $secondCollection->diffKeys($firstCollection);

this would be the value returned:

1 Collection {
2 #items: array:1 [
3 "description" => "Much shinier and bigger!"
4 ]
5 }

9.9 each(callable $callback)


The each method accepts a $callback which will be called on each item in the collection.
If the $callback returns false, the each method will break from its iterator and return a
reference back to the original Collection instance. The callback should define both an $item
and a $key parameter. For most use cases, the each method is functionally identical to PHP’s
foreach construct.

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.

9.10 filter(callable $callback = null)


The filter method applies a filter to the collection. An optional $callback can be supplied
to the filter method. If no $callback is supplied to the filter method, any value in
the collection that evaluates to false will be removed from the final collection. Supplying a
$callback allows developers to provide their own truth tests to determine if a value should be
included in the final collection that is returned. The filter method returns a modified copy of
the original Collection instance and does not modify the original collection.

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

18 return (strlen($item) >= 6);


19 });

9.11 first(callable $callback = null, $default =


null)

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)

9.14 forPage($page, $perPage)


The forPage method is used to implement pagination over collections. The forPage defines
two parameters: $page, which is used to tell the collection which “page” should be returned and
$perPage, which is used to control the number of items that should be on a given page. The
forPage method returns a new collection instance.

The following example demonstrates the forPage method:

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

9.14.1 Using chunk to achieve similar results


The chunk method can be used to achieve similar results. The following code sample will use the
same collection from the previous example, and chunk it into smaller collections each containing
two items.
Collections: The Public API 144

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):

1 // Get the fifth "page".


2 $fifthPage = $pages->get(4);

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)

9.16 get($key, $default = null)


The get method can be used to retrieve an item from the collection based of its $key. An optional
$default argument can be passed that will be returned if the given $key does not exists in the
collection. The $default argument can be a simple value, or a callback that will be evaluated
and the return value returned from the get method.
The following code sample demonstrates the use of the get method:
Collections: The Public API 146

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

9.17 groupBy($groupBy, $preserveKeys = false)


The groupBy method is used to group a collection based on a given value, represented by the
$groupBy parameter. An argument passed to $groupBy can be a simple string, representing
the value that the collection should be grouped by, or a callback that returns the value the
Collections: The Public API 147

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

The collection be grouped by the genus of each item like so:

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 $groupedByNameLength = $collection->groupBy(function($item, $key) {


2 return strlen($item['name']);
3 });

The $groupedByNameLength variable would be an instance of Collection and contain a value


similar to the following output:

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

18 'subspecies' => string 'C. l. arctos' (length=12)


19 'name' => string 'arctic wolf' (length=11)
20 8 =>
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)

9.17.1 Preserving keys with groupBy


By default, the groupBy method will not preserve the keys in the underlying collection when
grouping items. The following code sample shows how the groupBy method groups by default,
and the output:

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:

1 // Group the collection while preserving keys.


2 $grouped = $collection->groupBy('age', true);

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

9.19 implode($value, $glue = null)


The implode method will combine the items of the collection together. The Collection’s
implode method behaves differently than PHP’s implode³ function in that it can operate on
arrays of primitive data types as well as arrays of objects and arrays. Like PHP’s implode
function, the returned value is a string with the glue between each item.
The following code example demonstrates how to use the implode function to combine a simple
array of primitive data types. When using implode in this context, the only parameter required
is string that should be used to “glue” the items together:

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:

1 // The make() method returns a collection instance.


2 $users = factory('App\User', 3)->make();
3
4 $notification = $users->take(2)->implode('name', ', ') .
5 ' and '.$users->last()->name .
6 ' have recently followed you.';

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)

9.24 last(callable $callback = null, $default =


null)

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

9.25 lists($value, $key = null)


The lists method is an alias of the pluck method. The lists method is used to retrieve the a list
of values from the collection. It defines two parameters: $value and $key. The $value indicates
which property should become the value in the resulting collection and the $key parameter
indicates which property should become the key in the resulting collection.
The following code example will demonstrate the usage of the lists method to retrieve a
collection of the product names and versions:

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:

1 $products = $collection->lists('version', 'name');

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.26 map(callable $callback)


The map method applies a given $callback to each item in the collection. The $callback can
modify the item which will be added to a new collection. The map method does not modify
the original collection, but returns a new collection instance with all the changes. The provided
$callback should accept the $item and the items $key as it’s only arguments.
The following code example will transform the case of each string in the collection and return a
new collection instance:

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)

The original $collection collection will remain unchanged.

9.26.1 flatMap(callable $callback)


The flatMap method is used in the same way as the map method but will collapse the resulting
collection. The following two code examples are equivalent:

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

9.27 max($key = null)


The max method can be used to retrieve the maximum value of the given $key. By default, the
$key is null and will function in a similar way to PHP’s max⁶ function.

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)

9.29 min($key = null)


The min method is the logical opposite of the max method, and accepts the same number of
arguments. The min method can be used to retrieve the maximum value of the given $key. By
default, the $key is null and will function in a similar way to PHP’s min⁷ function.
The following code example highlights the usage of min without specifying a $key:

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.

9.30 pluck($value, $key = null)


The pluck method is used to retrieve the a list of values from the collection. It defines two
parameters: $value and $key. The $value indicates which property should become the value
in the resulting collection and the $key parameter indicates which property should become the
key in the resulting collection.
The following code example will demonstrate the usage of the pluck method to retrieve a
collection of the product names and versions:

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:

1 $products = $collection->pluck('version', 'name');

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)

9.32 prepend($value, $key = null)


The prepend method will add an a given $value to the beginning of the collection. You can
also supply an optional $key that will be used as the key for the new $value when adding an
item to the beginning of an associative array. The prepend method returns a reference to the
original collection instance.
The following code example demonstrates the usage of the prepend method:

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

1 // Create a new collection to work with.


2 $collection = collect([
3 'name' => 'Holiday Jumper',
4 'color' => 'Red'
5 ]);
6
7 // Add a new item to the beginning of the collection.
8 $collection->prepend('XL', 'size');

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 }

9.33 pull($key, $default = null)


The pull method will remove an item from the collection while returning its value. If the item
is not in the collection, the optional $default value will be returned. The pull method will
modify the original collection.

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.

9.35 put($key, $value)


The put method is used to add a new item to the collection with a given $key and $value. The
put method modifies the original Collection instance and returns a reference to it.

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

9.37 reduce(callable $callback, $initial = null)


The reduce method is to reduce a collection into only one item. It does this by iterating over
the collection and applying the $callback function on each item. The $callback function
should define two parameters: $carry and $item. The $carry variable will be initialized to
the previous result of the $callback function and the $item variable will contain the actual
collection item relevant to the current iteration. The $reduce method also defines a $initial
parameter.
Whatever value is given to $initial will become the value of the $carry variable on the first
call to the $callback function. If there are no items in the collection, the $initial value is
returned as the value of reduce.
Admittedly this can seem rather confusing. The following examples will demonstrate some of
the most basic uses of the reduce method. The returned value of the method call will appear
above the method call as a comment.

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):

Iteration Carry Item Result


1 0 (from $initial) 1 0
2 0 2 0
3 0 3 0
4 0 4 0
5 0 5 0

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:

Iteration Carry Item Result


1 1 (from $initial) 1 1
2 1 2 2
3 2 3 6
4 6 4 24
5 24 5 120

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)

9.40 search($value, $strict = false)


The search method is used to search the collection for a given $value. If the given $value is
found, the value’s corresponding key is returned. If the $value is not found in the collection,
the search method will return false. The search method also defines the parameter $strict
which will cause the search method to check the data types of the items in the collection with
the provided $value to make sure they match.
An argument passed for $value can either be a value, such as 4 or a callback function that
accepts both an $item and $key parameter. The following code examples will demonstrate both
uses of the search method. The returned value of each method call will appear above the method
call as a comment.

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)

9.43 slice($offset, $length = null, $preserveKeys =


false)

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

1 // Slice the collection starting starting at the


2 // fifth item from the end of the collection. The
3 // returned collection will contain the items
4 // 4, 5, 6, 7 and 8.
5 $sliced = $collection->slice(-5);

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:

1 // The returned collection will contain the items


2 // 2, 3 and 4.
3 $sliced = $collection->slice(1, 3);
4
5 // The returned collection will contain the items
6 // 1, 2 and 3.
7 $sliced = $collection->slice(0, 3);
8
9 // The returned collection will contain the items
10 // 1, 2, 3, 4 and 5.
11 $sliced = $collection->slice(0, -3);

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

1 // Slice the collection without preserving keys.


2 $sliced = $collection->slice(2, 3);
3
4 // Slice the collection while preserving keys.
5 $preservedKeySlice = $collection->slice(2, 3, true);

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

9.44 sort(callable $callback = null)


The sort method is used to sort the collection. If no $callback is provided, the collection will
be sorted using a case-insensitive “natural order” algorithm. An optional $callback can be
supplied to customize the comparison that is used when sorting the collection’s items. The sort
method does not affect the order of the original collection, but rather returns a new instance of
Collection.

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.

9.44.1 Custom Sorting Comparison Function


The $callback parameter can be utilized to provide a custom sorting comparison function. The
$callback should define two parameters, which are typically $a and $b. The $callback must
return an integer that is less than, equal to or greater than zero. If the $callback returns 0,
the arguments $a and $b are considered to be equal. If the $callback returns a value less than
0, $a is considered to be less than $b, and if $callback returns a value greater than 0, $a is
considered to be greater than $b.
The following example will use the $collection created earlier and demonstrate how to reverse
the sorting order:
Collections: The Public API 178

1 // Sort the collection in reverse order.


2 $sorted = $collection->sort(function($a, $b) {
3 if ($a == $b) {
4 return 0;
5 }
6
7 return ($a < $b) ? 1 : -1;
8 });

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

9.45 sortBy($callback, $options = SORT_REGULAR,


$descending = false)

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

It is possible to sort the $collection by name like so:

1 // Sort the users by name:


2 $sorted = $collection->sortBy('name');

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

To reverse the order, the following could be used:

1 $sorted = $collection->sort('name', SORT_REGULAR, true);

The $sorted collection would now be in the following order:


Collections: The Public API 181

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 // Sort the users by the number of followers.


2 $sorted = $collection->sortBy(function($value, $key) {
3 return count($value['followers']);
4 });

The $sorted collection would now be in the following order:

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:

1 // Sort the users by the number of followers.


2 $sorted = $collection->sortBy(function($value, $key) {
3 return count($value['followers']);
4 }, SORT_REGULAR, true);

9.45.1 sortBy Options


The $options parameter allows developers to change the sorting behavior of the sortBy
method. The accepted options are the same options that are defined for PHP’s sort⁸ function.
The following collection instance will be used throughout this section when describing the
behavior of the various options:

⁸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.

9.45.1.1 Sorting Flag Comparison Table

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.

Collection Keys and Values

Key Data Type Value


0 string a2.txt
1 string a1.txt
2 string a4.txt
3 object (Animal) KANGAROO
4 object (Animal) kangaroo
5 string a3.txt
6 integer 6
7 integer 5
8 object (Animal) macaw
9 string candice
10 string bob
11 string alice
12 object (Animal) zebra
Collections: The Public API 184

Sorting Flag Result Comparison

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):

1 // Sort the collection using the SORT_NUMERIC flag.


2 $sorted = $collection->sortBy(function($value, $key) {
3 return (string) $value;
4 }, SORT_NUMERIC);

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.

SORT_NUMERIC Result Comparison

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):

1 // Sort the collection using the SORT_STRING flag.


2 $sorted = $collection->sortBy(function($value, $key) {
3 return (string) $value;
4 }, SORT_STRING);

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

SORT_STRING Result Comparison

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

9.45.1.3.1 SORT_STRING and SORT_FLAG_CASE for Case Insensitivity

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):

1 // Sort the collection using the SORT_STRING and the


2 // SORT_FLAG_CASE flags.
3 $sorted = $collection->sortBy(function($value, $key) {
4 return (string) $value;
5 }, SORT_STRING | SORT_FLAG_CASE);

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.

SORT_STRING | SORT_FLAG_CASE Result Comparison

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):

1 // Sort the collection using the SORT_LOCALE_STRING flag.


2 $sorted = $collection->sortBy(function($value, $key) {
3 return (string) $value;
4 }, SORT_LOCALE_STRING);

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

SORT_LOCALE_STRING Result Comparison

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):

1 // Sort the collection using the SORT_NATURAL flag.


2 $sorted = $collection->sortBy(function($value, $key) {
3 return (string) $value;
4 }, SORT_NATURAL);

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.

SORT_NATURAL Result Comparison

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

9.45.1.5.1 SORT_NATURAL and SORT_FLAG_CASE for Case Insensitivity

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):

1 // Sort the collection using the SORT_NATURAL and the


2 // SORT_FLAG_CASE flags.
3 $sorted = $collection->sortBy(function($value, $key) {
4 return (string) $value;
5 }, SORT_NATURAL | SORT_FLAG_CASE);

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

SORT_NATURAL | SORT_FLAG_CASE Result Comparison

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

9.46 sortByDesc($callback, $options = SORT_REGULAR)


The sortByDesc method operates exactly the same as the sortBy method. The only differences
is that the sortByDesc method does not define a $descending parameter. The sortByDesc
method internally makes a call to the sortBy method passing true as the argument for the
$descending parameter.

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

9.47 splice($offset, $length = null, $replacement =


[])

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)

9.48 avg($key = null)


The avg method is a useful method for calculating the average of all items in the collection. The
avg method defines an optional $key parameter, which can be used to specify what property
of the collection should be averaged. If no key is provided, the method assumes the collection
contains numeric values and will average all items of the collection. If a key is provided, the
method will look for a matching array key or object property on all items in the array and then
average the value of those items. For example, the following code will a new Collection instance
and calculate the average of all items in the collection:
Collections: The Public API 191

1 // Calculate the average of some array.


2 $average = collect([5, 10, 15, 20])->avg();

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:

1 // Calculate the average price of all products.


2 $averagePrice = $products->avg('price');

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:

1 // Create a new collection where all the items


2 // are objects instead of nested arrays
3 // using the `map` method to convert.
4 $objectProducts = $products->map(function($item, $key) {
5 // Cast each product array into an object.
6 return (object)$item;
7 });

Now we can call the avg method on our new $objectProducts collection:

1 // Calculate the average price of all products.


2 $objectAveragePrice = $objectProducts->avg('price');

Like before, the value of $objectAveragePrice would contain the value 449.99.

9.48.1 Averaging Nested Collections


The avg method will also work on nested array items or object properties. You can specify which
nested property to average by using “dot” notation.
For example, in the following array of products it is still possible to use the avg method to
calculate the average product price:
Collections: The Public API 192

1 // Create a new collection with nested


2 // product details.
3 $nestedProductsDetails = collect([
4 [
5 'name' => 'Shiny New Tablet',
6 'details' => [
7 'price' => 799.99
8 ]
9 ],
10 [
11 'name' => 'Not A Stylus (Digital Stylus)',
12 'details' => [
13 'price' => 99.99
14 ]
15 ]
16 ]);
17
18 // Calculate the average product price by
19 // supplying the `$key` using "dot"
20 // notation.
21 $averageProductPrice = $nestedProductDetails->avg('details.price');

As with all the previous examples, the $averageProductPrice variable would contain the
value 449.99.

9.49 average($key = null)


The average method is simply an alias of the avg method, and can be used in exactly the same
way.

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

9.50 sum($callback = null)


The sum is a simple method that returns the sum of all items in a collection. It also defines a
$callback parameter which can be used to tell the sum method which values of the collection
should be added together. If no items are in the collection, the sum method will return 0.
The following code example shows the simplest way to use the sum method:
Collections: The Public API 193

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¹⁰.

1 // Create a new collection instance.


2 $collection = new Collection([
3 ['name' => 'Shirley', 'age' => 60],
4 ['name' => 'John', 'age' => 55]
5 ]);
6
7 // Convert the collection to JSON.
8 $jsonValue = $collection->toJson();

After the above code executes, $jsonValue would contain the following value:

1 [{"name":"Shirley","age":60},{"name":"John","age":55}]

Alternatively, a well-formatted value can be returned by passing in the JSON_PRETTY_PRINT


constant:

⁹http://php.net/manual/en/function.json-encode.php
¹⁰http://php.net/manual/en/json.constants.php
Collections: The Public API 197

1 // Create a new collection instance.


2 $collection = new Collection([
3 ['name' => 'Shirley', 'age' => 60],
4 ['name' => 'John', 'age' => 55]
5 ]);
6
7 // Convert the collection to JSON.
8 $jsonValue = $collection->toJson(JSON_PRETTY_PRINT);

This time, the $jsonValue would contain the following value:

1 [
2 {
3 "name": "Shirley",
4 "age": 60
5 },
6 {
7 "name": "John",
8 "age": 55
9 }
10 ]

9.52.0.1 toJson and Deeply Nested Data Structures

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"}

9.54 transform(callable $callback)


The transform is identical to the map method, but instead of returning a new Collection
instance, the transform method will modify the original collection instance. The transform
method will return a reference to the original collection instance.
The following code example will demonstrate the usage of the transform method:

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)

9.55 unique($key = null)


The unique method can be used to get all the unique items in the collection. It accepts an option
$key which can be used to further restrict which items are returned. The unique method returns
a new instance of Collection with the items it determined to be unique.
The following code example shows the basic usage of the unique method:

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)

9.57 where($key, $operator, $value = null)


The where method allows developers to filter a collection given a key value pair. It filters the
collection’s items by checking that the given $key has some value equal to the provided $value.
An argument can be supplied for the $operator parameter to control how the method internally
compares the given key against the value. The where method will return a new Collection
instance containing all the items the match the given criteria. The original collection instance
will not be modified in any way.
The following code example shows the basic usage of the where method:

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

24 // Get all animals with the genus 'Canis'


25 $animals = $collection->where('genus', 'Canis');

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

9.58 whereLoose($key, $value)


The whereLoose method operates similar to the where method. It filters the collection item’s by
checking that the given $key has some value equal to the provided $value. The whereLoose
method does not check to make sure the item’s value and the provided $value have the same
data type. This is the fundamental difference between the where and whereLoose methods.
The whereLoose method returns an instance of Collection and does not modify the original
collection in any way.
The following code example demonstrates the usage of the whereLoose method:
Collections: The Public API 205

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

1 $results = $collection->whereLoose('age', 2);


2
3 $results = $collection->where('age', 2, false);

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:

1 $firstCollection = collect(['green', 'red', 'yellow']);


2 $secondCollection = collect(['avocado', 'apple', 'banana']);
3
4 $combinedCollection = $firstCollection->combine($secondCollection);

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:

1 $firstCollection = collect(['green', 'red', 'yellow']);


2 $simpleArray = ['avocado', 'apple', 'banana'];
3
4 $combinedCollection = $firstCollection->combine($simpleArray);

Again, the value of $combinedCollection would be the same as before.

9.61 every($step, $offset = 0)


The every method can be used to retrieve a subset of a collection based on each items distance
from each other. It defines one required parameter $step and one optional parameter $offset.
An argument supplied for $step determines how far each item must be from each other in order
to be included in the final collection. In other words, the $step is used to say “get every N-th
item, where N is the $step.
An argument supplied for $offset (which is 0 by default) determines where to start when
building the final collection.
The following example creates a simple collection populated with the range of numbers from 0
to 10 (there will be eleven items in the collection):
Collections: The Public API 210

1 // Create a new collection.


2 $collection = collect(range(0,10));

We can retrieve all the even numbers using the every method like so:

1 // Retrieve the even numbers.


2 $evenNumbers = $collection->every(2);

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:

1 // Retrieve the odd numbers.


2 $oddNumbers = $collection->every(2,1);

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

1 // Create a new collection with a range


2 // of numbers.
3 $collection = collect(range(0,1000));
4
5 // Generate a subset of the collection.
6 $subset = $collection->every(50);

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.

The following example demonstrates the usage of the except method:


Collections: The Public API 212

1 // Create a new collection.


2 $collection = collect([
3 'first_name' => 'John',
4 'last_name' => 'Doe',
5 'password' => 'some_password'
6 ]);
7
8 // Retrieve all items from the collect
9 // except for the password.
10 $data = $collection->except(['password']);

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

1 // Create a new collection.


2 $collection = collect([
3 'first_name' => 'John',
4 'last_name' => 'Doe',
5 'password' => 'some_password'
6 ]);
7
8 // Retrieve only the first and last
9 // names from the collection.
10 $data = $collection->only(['first_name', 'last_name']);

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:

1 // Create a new collection.


2 $people = collect([
3 ['id' => 12, 'name' => 'Alice', 'age' => 26],
4 ['id' => 52, 'name' => 'Bob', 'age' => 34],
5 ['id' => 14, 'name' => 'Chris', 'age' => 26]
6 ]);

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.

9.65 whereIn($key, array $values, $strict = true)


The whereIn method is used to filter the collection based on a given $key and an array of
the possible $values that the $key can have. The method also defines an optional $strict
parameter, which when an argument with a truth value of true is supplied, will cause the
method to check the types of each item in the collection against the types in the supplied $values
array ($strict is set to true by default). This method does not change the original Collection
instance and will return a new, modified, Collection instance.
The following examples will use the following collection to demonstrate the whereIn method:

1 // Create a new collection.


2 $people = collect([
3 ['name' => 'Alice', 'age' => 26],
4 ['name' => 'Bob', 'age' => 34],
5 ['name' => 'Chris', 'age' => 26]
6 ]);

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

1 $results = $people->whereIn('age', [26]);

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:

1 // Notice that the value in the array is


2 // a string, not an integer.
3 $results = $people->whereIn('age', ['26']);

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:

1 // Disable type checking by supplying an


2 // argument that evaluates to false
3 // for the $strict parameter.
4 $results = $people->whereIn('age', ['26'], false);

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).

9.66 whereInLoose($key, array $values)


The whereInLoose method is similar to the whereIn method in that both methods can be
used to filter the collection based on a given $key and an array of possible $values that the
$key can have. The whereLoose method by default performs type checking to determine if
Collections: The Public API 217

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.

The same sample will be used from the whereIn method:

1 $people = collect([
2 ['name' => 'Alice', 'age' => 26],
3 ['name' => 'Bob', 'age' => 34],
4 ['name' => 'Chris', 'age' => 26]
5 ]);

The following two method calls are identical in their results:

1 $collectionA = $people->whereIn('age', ['26'], false);


2 $collectionB = $people->whereInLoose('age', ['26']);
10. Collections: The Static API
The Collection class provides only one static method: a convenient method to create a new
collection.

10.1 make($items = [])


The make static method creates a new instance of a collection with the provided $items
(assuming that the provided $items is in itself not an instance of Collection). The following
code sample highlights the usage of the make static method:

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

11.1.1 add($key, $message)


The add method adds a new message to the MessageBag instance. The message is identified
by a given $key and contains the value $message. The add method returns a reference to the
current MessageBag instance.
The following code example demonstrates how to add messages to a MessageBag instance:

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 $messageBag->add('hello', 'This is a different hello');

And the output would then change to the following:


Message Bags 222

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)

11.1.1.1 Notes on Keys

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 <input type="text" name="username" />

Messages relating the username field could be stored like so:

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

11.1.2 all($format = null)


The all method can be used to retrieve all the messages according to a given $format. The
$format is null by default, which will cause the all method to use the format stored within
the MessageBag instance (which can be retrieved using the getFormat method). Alternatively,
developers can specify their own $format to customize the results each time the all method is
executed. The all method will return an array containing all of the formatted messages.
The following code will create a new MessageBag instance with some default messages:
Message Bags 223

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:

1 The message was: :message

1 $messages = $messageBag->all('The message was: message');

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).

11.1.5 first($key = null, $format = null)


The first method will return the first message in the MessageBag instance for a given $key.
If the $key is null the first method will return the first message in the MessageBag instance.
If there are no messages stored within the message bag, the first method will return an
empty string. The first method also accepts a $format parameter, which allows developers to
customize the format that is used when transforming the message (which by default is just the
default message).
The following examples will demonstrate the usage of the first method. The result of the
method call will appear above the method call as a comment:

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

11.1.6 get($key, $format = null)


The get method can be used to retrieve all the messages for a given $key with the specified
$format. The $format is null by default, which will cause the get method to use the format
stored within the MessageBag instance (which can be retrieved using the getFormat method).
Alternatively, developers can specify their own $format to customize the results each time the
get method is executed. The get method will return an array containing all of the formatted
messages.
The following example code will create a new MessageBag instance that can be used to retrieve
messages from:

1 // Create a new MessageBag instance.


2 $messageBag = new MessageBag;
3
4 // Add items to the MessageBag
5 $messageBag->add('first', 'The very first message');
6 $messageBag->add('first', 'The second message');
7 $messageBag->add('second', 'I should not be in the output');

The following code will retrieve all of the messages with the given format:

1 The message was: :message

1 $messages = $messageBag->get('first', 'The message was: message');

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)

11.1.10 has($key = null)


The has method can be used to determine if messages exist within the MessageBag instance for
a given $key. The has method returns true if messages exist for the given $key, and returns
false if no messages exist.

The following examples demonstrate the usage of the has method:

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 ];

can be merged with the following message bag:

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:

1 // Merge the $arrayToMerge with the $messages


2 $messages->merge($arrayToMerge);
3
4 // Get the messages as an array.
5 $messageArray = $messages->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=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)

Because the MessageBag class implements the MessageProvider interface, a MessageBag


instance can be supplied as the argument for the $messages parameter:
Message Bags 231

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)

11.1.15 setFormat($format = ':message')


The setFormat is the logical opposite of the getFormat method. It allows developers to
customize the format used by all methods of the MessageBag instance. It defines a $format
parameter, whose argument will be used as the value of the new format. If the setFormat
method is called without supplying a value for $format, it will reset the format to the default
value (because of the parameter’s default value).

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):

1 string '{"first":["The very first message","The second message"],


2 "second":["I should not be in the output"]}' (length=100)

Alternatively, a well-formatted value can be returned by passing in the JSON_PRETTY_PRINT


constant:

1 // Convert the MessageBag to formatted JSON.


2 $jsonValue = $messageBag->toJson(JSON_PRETTY_PRINT);

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 }

11.1.17.1 toJson and Deeply Nested Data Structures

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:

1 {"first":["The first message"]}

11.2 View Error Bags


The Illuminate\Support\ViewErrorBag class is generally used to communicate error mes-
sages with views and responses. The ViewErrorBag itself is essentially a container for Illu-
minate\Contracts\Support\MessageBag implementation instances.

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:

1 <div class="alert alert-danger">


2 <p>There were some errors that need to be fixed!</p>
3 <ul>
4 <li>The secret field is required.</li>
5 </ul>
6 </div>

If the user did not supply either a username or a secret, the following HTML code would have
been generated:

1 <div class="alert alert-danger">


2 <p>There were some errors that need to be fixed!</p>
3 <ul>
4 <li>The username field is required.</li>
5 <li>The secret field is required.</li>
6 </ul>
7 </div>

11.2.1 ViewErrorBag Public API


The ViewErrorBag exposes few methods itself in its public API (at the time of writing, only
five methods exist intended for public use). However, the ViewErrorBag will redirect calls to
methods that do not exist explicitly on the ViewErrorBag instance to the default MessageBag
instance. Any public method that can be called on a MessageBag instance can be called on the
default MessageBag instance without having to do any extra work:
Message Bags 236

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

27 // Get the count from $viewErrorBag


28 //
29 // 1
30 $messageCount = count($viewErrorBag);

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.

11.2.1.2 getBag($key = null)

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

1 // Request a MessageBag that has not been set yet.


2 $messageBagInstance = $viewErrorBag->getBag('paymentErrors');

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.

1 // Get the 'formErrors' MessageBag instance.


2 $formErrors = $viewErrorBag->formErrors;

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)

11.2.1.4 hasBag($key = 'default')

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

11.2.1.5 put($key, Illuminate\Contracts\Support\MessageBag $bag)

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:

1 // Add a new MessageBag instance without


2 // using the 'put' method.
3 $viewErrorBag->anotherKey = new MessageBag;

At this point, the $viewErrorBag instance would now contain two MessageBag instances with
the keys somekey and anotherKey.

11.2.1.5.1 Resetting MessageBag Messages

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:

1 // Create a different MessageBag instance.


2 $newMessageBag = new MessageBag([
3 'username' => [
4 'The username is required.'
5 ]
6 ]);
7
8 // Get the 'somekey' MessageBag before changing it.
9 $beforeChange = $viewErrorBag->getBag('somekey');
10
11 // Change the MessageBag instance.
12 $viewErrorBag->put('somekey', $newMessageBag);
13
14 // Get the 'somekey' MessageBag after changing it.
15 $afterChange = $viewErrorBag->getBag('somekey');

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

$beforeChange MessageBag Output

1 object(Illuminate\Support\MessageBag)[142]
2 protected 'messages' =>
3 array (size=0)
4 empty
5 protected 'format' => string ':message' (length=8)

$afterChange MessageBag Output

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:

1 // Create a new array containing sample data


2 $testArray = [
3 'first' => 'The first value',
4 'second' => 'The second value',
5 'third' => 'The third value'
6 ];
7
8 // Create a new stdClass instance containing sample data
9 $testObject = new stdClass;
10 $testObject->first = 'The first value';
11 $testObject->second = 'The second value';
12 $testObject->third = 'The third value';

We can access data from the $testArray like so:

1 // Retrieve the 'first' item


2 $value = $testArray['first'];

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”):

1 // Retrieve the 'first' property


2 $value = $testObject->first;

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

1 // Will raise an exception


2 $value = $testArray['does_not_exist'];

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:

1 // Will raise an exception


2 $value = $testObject->doesNotExist;

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:

1 // Get a value from an array, or a default value


2 // if it does not exist.
3
4 if (array_key_exists('does_not_exist', $testArray))
5 {
6 $value = $testArray['does_not_exist'];
7 } else {
8 $value = 'Some default value';
9 }
10
11
12 // Get a value from an object, or a default value
13 // if it does not exist.
14
15 if (property_exists('doesNotExist', $testObject))
16 {
17 $objectValue = $testObject->doesNotExist;
18 } else {
19 $objectValue = 'Some default value';
20 }

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:

1 // Some example data, which could be obtained from


2 // any number of sources.
3 $testArray = [
4 'first' => 'The first value',
5 'second' => 'The second value',
6 'third' => 'The third value'
7 ];
8
9 // Create a new Fluent instance.
10 $fluent = new Fluent($testArray);

Now that we have a Fluent instance, data can be retrieved just like an object or an array:

1 // Accessing a value like an array.


2 $value = $fluent['first'];
3
4 // Accessing a value like an object.
5 $secondValue = $fluent->first;

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.

12.1 Fluent Public API


The following sections will highlight the usage of the various public methods that the Fluent
class provides. There are, however, some omissions in this section, namely the methods
required to implement PHP’s ArrayAccess¹ interface. The examples that follow will assume
the following test array and object, unless stated otherwise:
¹http://php.net/manual/en/class.arrayaccess.php
Fluent 246

1 // A test array for use with Fluent.


2 $testArray = [
3 'first' => 'The first value',
4 'second' => 'The second value',
5 'third' => 'The third value'
6 ];
7
8 // A test object for use with Fluent.
9 $testObject = new stdClass;
10 $testObject->first = 'The first value';
11 $testObject->second = 'The second value';
12 $testObject->third = 'The third value';

12.1.1 get($key, $default = null)


The get method will return the value associated with the provided $key. If the $key does not
exist, the $default value will be returned (which is null by default).
Retrieving values from a Fluent instance:

1 $fluent = new Fluent($testArray);


2
3 // The first value
4 $message = $fluent->get('first');
5
6 $fluent = new Fluent($testObject);
7
8 // The first value
9 $message = $fluent->get('first');
10
11 // null
12 $willBeNull = $fluent->get('does_not_exist');

The $default value is evaluated using the value helper function, meaning that it can be the
result of a function:

1 $fluent = new Fluent($testArray);


2
3 // Does not exist yet!
4 $message = $fluent->get('does_not_exist', function() {
5 return 'Does not exist yet!';
6 });

12.1.1.1 Fluent and Closures

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

1 $testObject = new stdClass;


2 $testObject->method = function() {
3 return 'Hello, world!';
4 };
5
6 $fluent = new Fluent($testObject);
7
8 $message = $fluent->method;
9
10 // Or even this:
11
12 $message = $fluent->get('method');

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:

1 $fluent = new Fluent($testObject);


2
3 $attributes = $fluent->getAttributes();

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:

1 $fluent = new Fluent($testObject);


2
3 $jsonValue = $fluent->toJson();

would be converted into the following JSON, stored in the $jsonValue variable:

1 {"first":"The first value","second":"The second value","third":


2 "The third value","method":{}}

Alternatively, a well-formatted value can be returned by passing in the JSON_PRETTY_PRINT


constant:

1 $fluent = new Fluent($testObject);


2
3 $jsonValue = $fluent->toJson(JSON_PRETTY_PRINT);

This time, the $jsonValue would contain the following value:


²http://php.net/manual/en/class.jsonserializable.php
³http://php.net/manual/en/function.json-encode.php
⁴http://php.net/manual/en/json.constants.php
Fluent 249

1 {
2 "first": "The first value",
3 "second": "The second value",
4 "third": "The third value",
5 "method": {}
6 }

12.1.5.1 toJson and Deeply Nested Data Structures

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 $fluent = new Fluent($testObject);


2
3 // Replace 512 with the desired depth.
4 $jsonValue = json_encode($fluent->jsonSerialize(), 0, 512);
13. Macros
Macros are a way to reduce the lines of code a developer has to write, and can be traditionally
thought of as “shortcuts”. Laravel generally uses macros to add, or inject, functions into various
classes at runtime. Developers familiar with C# can see the similarities between C#’s extension
methods and Laravel’s macros.
For example, the following C# will add a new method CountWords to the String class:

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

13.1 Default Classes That Support Macros


Classes allow for macros to be created by using the \Illuminate\Support\Traits\Macroable
trait. There are, at the time of this writing, six classes that ship with support for macros:

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.

13.2 Creating a Macro


To create a macro, first locate the desired class to create a macro for. In the following examples, a
rot13 macro will be created for the \Illuminate\Support\Str class. The first helper function
will be a wrapper of PHP’s str_rot13 function, which performs the ROT13 encoding¹ on a given
string.
The macro function is easily created like so:

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

In the above example, $value would be assigned the value grfg.

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:

1 Cannot access protected property Illuminate\Support\Str::$studlyCache

13.3 Macroable Methods


The following methods are available in the Macroable trait:

macro($name, callable $macro)


The macro method is used to create a macro, and can be examined in the previous code
examples.

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.

13.3.1 Important Notes On __call and __callStatic


Because Macroable depends on both the __call and __callStatic methods to be available
for it’s own use, it is currently not possible to use the Macroable trait in a class that also
requires returning a value from either __call or __callStatic without modifying the parent
class’s __call or __callStatic methods to accommodate the macro features. However,
accommodating the macro features in a class that requires one, or both of the above magic
methods is quite simple:

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

13.3.2 Notes on Eloquent Builder


Even though the Illuminate\Database\Eloquent\Builder class supports macros, it does
not use the Macroable trait. The Builder class exposes the following public methods for
interacting with macros:

macro($name, Closure $callback)


Adds a new macro to the Builder with the given $name and $callback.

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.

14.1 Facade Aliases and Importing Facades


Each facade has an alias. An alias in PHP is just a shortcut to a longer class name. For example,
when we use something as something else, we are creating a class alias:

1 use Some\ReallyReallyLongClassName as ShorterName;

In the above example ShorterName is an alias of ReallyReallyLongClassName. Laravel


creates aliases for all of the facades automatically, and the entire list of them can be found in the
aliases array in the config/app.php file. The aliases that Laravel creates are in the global
namespace, which means that developers can write code that looks like this:

1 <?php namespace App\Http\Controllers;


2
3 use Input;
4
5 // Other code here.

instead of having to write code that references the full namespace:


¹Some facades define additional static methods that may are not necessarily part of the underlying component or class. In these instances,
the static method (that belongs to the facade) is called directly. One such example is the Cookie facade.

256
Facades 257

1 <?php namespace App\Http\Controllers;


2
3 use Illuminate\Support\Facades\Input;
4
5 // Other code here.

Fully Qualified Names vs. Aliases


Fully qualified names, such as Illuminate\Support\Facades\Input are longer, but
offer greater clarity on what class is being imported. At the end of the day, it comes
down to personal preference.

14.2 Using Facades


Laravel’s facades are used just like any other static class, with the exception that facades are
redirecting method calls to an actual class instance. Facades are typically imported at the top of
the source file, along with any other classes that are required.
For example, using a facade to retrieve an item from the cache:

1 <?php namespace App\Http\Controllers;


2
3 use Illuminate\Support\Facades\Cache;
4
5 class ExampleController extends Controller {
6
7 public function getIndex()
8 {
9 $cachedItem = Cache::get('some_cache_item');
10 }
11
12 }

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

1 <?php namespace App\Http\Controllers;


2
3 use Illuminate\Cache\Repository as CacheRepository;
4
5 class ExampleController extends Controller {
6
7 /**
8 * The cache repository.
9
10 * @var CacheRepository
11 */
12 protected $cacheRepository = null;
13
14 public function __construct(CacheRepository $cacheRepository)
15 {
16 $this->cacheRepository = $cacheRepository;
17 }
18
19 public function getIndex()
20 {
21 $cachedItem = $this->cacheRepository->get('some_cache_item');
22 }
23
24 }

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.

14.3 Creating Facades


It may become necessary when developing certain applications, or when creating packages to
write a facade class. Creating a facade class is fairly simple. The first thing that is required is
some actual concrete class the facade will be accessing. For this example, the following class will
be used:
Facades 259

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:

1 <?php namespace App\Http\Controllers;


2
3 use Calculator;
4
5 class TestController extends Controller {
6
7 public function getIndex()
8 {
9 // We will create an instance, instead of having it supplied
10 // through the constructor.
11 $calculator = new Calculator;
12
13 $result = $calculator->add(1, 2);
14 }
15
16 }

now using the facade:


Facades 261

1 <?php namespace App\Http\Controllers;


2
3 use Math;
4
5 class TestController extends Controller {
6
7 public function getindex()
8 {
9 $result = Math::add(1, 2);
10 }
11
12 }

14.3.1 Creating a Facade Alias


Creating a facade alias is completely optional. Package developers often include the following
steps in their package installation instructions, but it is not required for a facade to work.
In the config/app.php file, there is an aliases configuration entry. By default it will look like
this:

1 // Other configuration items.


2
3 'aliases' => [
4
5 'App' => 'Illuminate\Support\Facades\App',
6 'Artisan' => 'Illuminate\Support\Facades\Artisan',
7 'Auth' => 'Illuminate\Support\Facades\Auth',
8 'Blade' => 'Illuminate\Support\Facades\Blade',
9 'Bus' => 'Illuminate\Support\Facades\Bus',
10 'Cache' => 'Illuminate\Support\Facades\Cache',
11 'Config' => 'Illuminate\Support\Facades\Config',
12 'Cookie' => 'Illuminate\Support\Facades\Cookie',
13 'Crypt' => 'Illuminate\Support\Facades\Crypt',
14 'DB' => 'Illuminate\Support\Facades\DB',
15 'Event' => 'Illuminate\Support\Facades\Event',
16 'File' => 'Illuminate\Support\Facades\File',
17 'Gate' => 'Illuminate\Support\Facades\Gate',
18 'Hash' => 'Illuminate\Support\Facades\Hash',
19 'Input' => 'Illuminate\Support\Facades\Input',
20 'Lang' => 'Illuminate\Support\Facades\Lang',
21 'Log' => 'Illuminate\Support\Facades\Log',
22 'Mail' => 'Illuminate\Support\Facades\Mail',
23 'Password' => 'Illuminate\Support\Facades\Password',
24 'Queue' => 'Illuminate\Support\Facades\Queue',
25 'Redirect' => 'Illuminate\Support\Facades\Redirect',
Facades 262

26 'Redis' => 'Illuminate\Support\Facades\Redis',


27 'Request' => 'Illuminate\Support\Facades\Request',
28 'Response' => 'Illuminate\Support\Facades\Response',
29 'Route' => 'Illuminate\Support\Facades\Route',
30 'Schema' => 'Illuminate\Support\Facades\Schema',
31 'Session' => 'Illuminate\Support\Facades\Session',
32 'Storage' => 'Illuminate\Support\Facades\Storage',
33 'URL' => 'Illuminate\Support\Facades\URL',
34 'Validator' => 'Illuminate\Support\Facades\Validator',
35 'View' => 'Illuminate\Support\Facades\View',
36 ],
37
38 // Other configuration items.

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:

1 // Previous alias entries.


2
3 'Math' => 'Our\Applications\Namespace\Math',

Aliasing Other Classes


Classes, other than facades, can be added to the aliases configuration entry. This
will cause them to be available under whatever name was provided, and in the global
namespace. Although this can be convenient and useful thing to do, other options
should be examined first.

14.4 Facade Class Reference


The following tables will list all the facades that are available by default. In addition, they
will display the name of the service container binding as well as the class behind the facade.
If a particular facade provides additional methods (that are not necessarily available in the
underlying class), it will appear in the third table “Facades Providing Additional Methods”. Any
additional methods will be explained later in the section.
Facades 263

Facade Service Container Binding

Facade Service Container Binding


App app
Artisan Illuminate\Contracts\Console\Kernel
Auth auth
Blade See “Notes on Blade”
Bus Illuminate\Contracts\Bus\Dispatcher
Cache cache
Config config
Cookie cookie
Crypt encrypter
DB db
Event events
File files
Gate Illuminate\Contracts\Auth\Access\Gate
Hash hash
Input request
Lang translator
Log log
Mail mailer
Password auth.password
Queue queue
Redirect redirect
Redis redis
Request request
Response Illuminate\Contracts\Routing\ResponseFactory
Route router
Schema See “Notes on Schema”
Session session
Storage filesystem
URL url
Validator validator
View view

Facade Class Reference

Facade Resolved Class


App Illuminate\Foundation\Application
Artisan App\Console\Kernel
Auth Illuminate\Auth\AuthManager
Blade Illuminate\View\Compilers\BladeCompiler
Bus Illuminate\Bus\Dispatcher
Cache Illuminate\Cache\CacheManager
Config Illuminate\Config\Repository
Cookie Illuminate\Cookie\CookieJar
Crypt Illuminate\Encryption\Encrypter
DB Illuminate\Database\DatabaseManager
Facades 264

Facade Class Reference

Facade Resolved Class


Event Illuminate\Events\Dispatcher
File Illuminate\Filesystem\Filesystem
Gate Illuminate\Auth\Access\Gate
Hash Illuminate\Hashing\BcryptHasher
Input Illuminate\Http\Request
Lang Illuminate\Translation\Translator
Log Illuminate\Log\Writer
Mail Illuminate\Mail\Mailer
Password Illuminate\Auth\Passwords\PasswordBroker
Queue Illuminate\Queue\QueueManager
Redirect Illuminate\Routing\Redirector
Redis Illuminate\Redis\Database
Request Illuminate\Http\Request
Response Illuminate\Routing\ResponseFactory
Route Illuminate\Routing\Router
Schema Illuminate\Database\Schema\MySqlBuilder
Session Illuminate\Session\SessionManager
Storage Illuminate\Contracts\Filesystem\Factory
URL Illuminate\Routing\UrlGenerator
Validator Illuminate\Validator\Factory
View Illuminate\View\Factory

Facades Providing Additional Methods

Facade Number of Additional Methods


Cookie 2
Input 2
Schema 2

14.4.1 Notes on Blade


Most facades request a concrete class implementation from the service container based off of
some abstract string representation. However, the Blade facade retrieve an Illuminate\View\Engines
\EngineResolver instance from the Illuminate\View\Factory.

The Illuminate\View\Engines\EngineResolver is a class that returns template compilers


based on a given key name. By default, the following compilers and engines are available:

Compiler/Engine Name Concrete Class Implementation


php Illuminate\View\Engines\PhpEngine
blade Illuminate\View\Compilers\BladeCompiler

Developers can manually create an instance of the BladeCompiler themselves like so (this
Facades 265

sample is provided for demonstration purposes):

1 <?php
2
3 use Illuminate\Support\Facades\App;
4
5 $bladeCompiler = App::make('view')->getEngineResolver()
6 ->resolve('blade')->getCompiler();

14.4.2 Notes on Schema


Like the Blade facade, the Schema facade does not simply resolve some instance from the service
container. The Schema facade returns an instance of Illuminate\Database\Schema\Builder
configured to use the default connection that appears in the database database configuration.

14.4.3 Additional Cookie Methods


The Cookie facade defines two additional methods. These methods access other, related,
components. These methods exist to simplify accessing related components.

14.4.3.1 has($key)

The has function will check if a cookie with the given $key exists for the current request.

14.4.3.2 get($key, $default = null)

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.

14.4.4 Additional Input Methods


The Input facade defines one extra method. Facades define extra methods to provide simpler
access to underlying sub-systems, or to call functions on other, related components.

14.4.4.1 get($key = null, $default = null)

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 Additional Schema Methods


The Schema facade defines one extra method. Facades define extra methods to provide simpler
access to underlying sub-systems, or to call functions on other, related components.

14.4.5.1 connection($name)

The connection method will return a new schema builder (Illuminate\Database\Schema\Builder)


instance for the given connection. The $name is the name of the connection as it appears in the
database configuration file.

14.5 Resolving the Class Behind a Facade


It is possible to quickly resolve the class behind a facade. Facades expose a public method
getFacadeRoot which will return the instance of the underlying object the facade is forwarding
method calls to. It is convenient that getFacadeRoot returns an object instance because PHP’s
get_class³ method can then be used to retrieve the fully-qualified name of the facade’s
underlying class implementation.

1 // Getting the class name of the underlying facade instance.


2 $className = get_class(Auth::getFacadeRoot());

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 }

Potrebbero piacerti anche