Courses

PHP for Laravel Developers

Callback Functions or Closures

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Learn about callback function syntax
- Understand closure parameter and use mechanisms
- Explore short arrow function syntax
- Examine practical uses of anonymous functions

So-called callback functions, "callables" or "closures" are used in Laravel very often, so we need to understand all the details behind their syntax.

Take a look at these Laravel examples.

You can provide the route functionality in a callback function without any Controller:

Route::get('/greeting', function () {
return 'Hello World';
});

You can use Collections to map through data with your custom logic defined in a callback function:

$socialLinks = collect([
'Twitter' => $user->link_twitter,
'Facebook' => $user->link_facebook,
'Instagram' => $user->link_instagram,
])
->filter()
->map(fn ($link, $network) => '<a href="' . $link . '">' . $network . '</a>')
->implode(' | ');

In Eloquent, you may use the chunk() method with a closure, too:

use App\Models\Flight;
use Illuminate\Database\Eloquent\Collection;
 
Flight::chunk(200, function (Collection $flights) {
foreach ($flights as $flight) {
// ...
}
});

So, what are the main things we need to know about them?


When Can We Use Them As Parameters?

When the method is defined with the parameters types as...

The full lesson is only for Premium Members.
Want to access all 16 text lessons of this course? (52 min read)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord