Factory Callbacks and Closure-Based Guards in Laravel


June 7th, 2018

Factory Callbacks and Closure-Based Guards in Laravel

Two undocumented (before today anyhow) features were recently added to the Laravel 5.6 documentation, and they are both fantastic!

First, factory callbacks allow you to perform additional tasks after making or creating a model:

Thanks to @driesvints for documenting this handy new feature… ✌️ pic.twitter.com/UZ01NxR6yz

— Taylor Otwell ????‍???? (@taylorotwell) June 7, 2018

I mentioned these helpers in Going Deeper with Factory States, and at the time these methods weren’t documented yet. There are four methods now documented thanks to Dries Vints:

1// Callback for factories
2$factory->afterMaking(App\User::class, function ($user, $faker) {
3 // ...
6$factory->afterCreating(App\User::class, function ($user, $faker) {
7 $user->accounts()->save(factory(App\Account::class)->make());
10// Callbacks for factory states
11$factory->afterMakingState(App\User::class, 'delinquent', function ($user, $faker) {
12 // ...
15$factory->afterCreatingState(App\User::class, 'delinquent', function ($user, $faker) {
16 // ...

These callbacks are a clean way to save relational data automatically after creating a new model via a factory.

The second feature that was previously undocumented is Closure-based guards for request authentication:

Simple, Closure based authentication for request authentication in Laravel: https://t.co/PGG1MPVkhd … have used it several times myself but wasn't documented. ????

— Taylor Otwell ????‍???? (@taylorotwell) June 7, 2018

Adding the Auth::viaRequest within one of your service provider’s boot() method is the simplest way to implement custom HTTP authentication:

1Auth::viaRequest('custom-token', function ($request) {
2 return User::where('token', $request->token)->first();

You can then reference the custom guard in your app’s config/auth.php guards config:

1'guards' => [
2 'api' => [
3 'driver' => 'custom-token',
4 ],

Laravel is by far one of the most well-documented frameworks in existence, and thanks to individual community members, the documentation keeps getting better!

The documentation can’t possibly cover everything, but with the number of new features and changes in each release, there’s always room for adding new features to the documentation repo.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.