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