n How to use Factory callbacks in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Example How to use Factory callbacks in Laravel:

in laravel you can provide Factory Callback functions to perform some action after record is inserted.


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


Factory callbacks are registered using the afterMaking and afterCreating methods and allow you to perform additional tasks after making or creating a model. You should register these callbacks by defining a configure method on the factory class. This method will automatically be called by Laravel when the factory is instantiated:

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
     * The name of the factory's corresponding model.
     * @var string
    protected $model = User::class;

     * Configure the model factory.
     * @return $this
    public function configure()
        return $this->afterMaking(function (User $user) {
        })->afterCreating(function (User $user) {

    // ...

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook