Factory Callbacks and Closure-Based Guards in Laravel

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:

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:

// Callback for factories
$factory->afterMaking(App\User::class, function ($user, $faker) {
    // ...

$factory->afterCreating(App\User::class, function ($user, $faker) {

// Callbacks for factory states
$factory->afterMakingState(App\User::class, 'delinquent', function ($user, $faker) {
    // ...

$factory->afterCreatingState(App\User::class, 'delinquent', function ($user, $faker) {
    // ...

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:

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

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

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

'guards' => [
    'api' => [
        'driver' => 'custom-token',

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: News


Join 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full Stack PHP (Mid-Level/Senior) Programmer
Software Developer
Remote, (US & Canada Only)
Patient Prism
Web Application Developer
Chicago Loop
Leading Real Estate Companies of the World
Multiple Laravel Developers (Part-Time)
Remote, USA Only
The Great Escape Room
Software Developer
Remote (US & Canada)