Creating and Using Factory in Laravel

This flash explanation is tested on Laravel 7.x

Note

Laravel has a feature called model factories that gives you the ability to send fake data for your models. It is very helpful for testing and seeding fake data into your database to see your methods in action.

The explanation will be brief and in the point without complications, I will apply the factory tip on the basic User Model.

Let’s suppose that you have already started an Laravel app, with the the default User Model that come with Laravel.

In your command line interface type:

php artisan tinker

That artisan command will gives you the ability to check your database fields of table “USERS”

Something like this:

php artisan tinker output

To check your first user type in your CLI:

User::first()

We use our User Model and first() to call our first registered user.

That’s will give us something like that:

Check your first user.

So the last thing to add the fake data to our users table using factory, Laravel make it simple as possible. Let’s suppose that you want add 250 users to your database using your model. So type after:

factory(App\User::class, 250)->create();

And this command will add 250 users easily and quickly.

Factory will saves you a lot of time for testing and see your code in action, try it in your next projects.
Hope it’s helpful for someone

Leave a Reply

Your email address will not be published. Required fields are marked *