Skip to main content

Callback Functions or Closures

Premium
4 min read

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 of our courses? (30 h 41 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

N
Napping7269 ✓ Link copied!

In the filament example, what benefit do we get from having a function inside a var? We can just have a helper function and get the same result.

M
Modestas ✓ Link copied!

What do you mean by function inside a var? I'm not sure I understood what are you referring to here

N
Napping7269 ✓ Link copied!

"Assign Function to a Variable" it's from the article...

N
Nerijus ✓ Link copied!

Helper is when you use it in many places through your project. In this case it's only used in one file.

N
Napping7269 ✓ Link copied!

I mean what's the benifit of writing $getSpanValue = function ... instead of just writing function getSpanValue(){}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.