Chapter 17. Helpers and Collections
We’ve already covered many global functions throughout the book: little helpers that make it easier to perform common tasks, like dispatch()
for Jobs, event()
for Events, app()
for dependency resolution, and many more. We also talked a bit about Laravel’s collections, or arrays on steroids, in Chapter 8.
In this chapter we’ll cover some of the more common and powerful helpers and some of the basics of programming with collections.
Helpers
You can find a full list of the helpers Laravel offers in the helpers docs, but we’re going to cover a few of the most useful functions here.
Arrays
PHP’s native array manipulation functions give you a lot of power, but sometimes there are common manipulations we want to make that require unwieldy loops and logic checks. Laravel’s array helpers make a few common array manipulations much simpler:
array_first($array, $closure, $default = null)
-
Returns the first array value that passes a test, defined in a closure. You can optionally set the default value as the third parameter:
$people
=
[
[
'email'
=>
'm@me.com'
,
'name'
=>
'Malcolm Me'
],
[
'email'
=>
'j@jo.com'
,
'name'
=>
'James Jo'
]
];
$value
=
array_first
(
$people
,
function
(
$key
,
$person
)
{
return
$person
[
'email'
]
==
'j@jo.com'
;
});
array_get($array, $key, $default = null)
-
Makes it easy to get values out of an array, with two added benefits: it won’t throw an error if you ask for a key that doesn’t exist (and you can provide defaults with the third ...
Get Laravel: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.