Database Seeding is a process you can rely on anytime you want to generate some entries in your database. Seeding a database simply means providing an initial set of database when it’s created. It’s particulary useful for demo purposes or even for important entries such as an initial admin account.

To seed a database with Masonite , you should follow some steps:

  • Craft a model
  • Craft the seed
  • Register the migrations in Database Seeder file
  • Describe your entries in factories.py

Craft the model

To seed data, we need a model and the entries we are going to use. To explain, things easily I will suppose that we want to generate some dummies data about a blog.

craft model Post -m
# app/Post.py
"""Post Model."""

from config.database import Model


class Post(Model):
    """Post Model."""
    __table__ = 'posts'
    __fillable__ =['author','title','description']

The -m flag in the craft command add a file migration for the model.

#database/migrations/2020_03_09_205230_create_posts_table.py 
from orator.migrations import Migration


class CreatePostsTable(Migration):

    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create('posts') as table:
            table.increments('id')
        	#new lines
            table.string('author')
            table.string('title')
            table.string('text')

            table.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop('posts')

Craft the seed

craft seed posts

This will create a file called post_table_seeder.py

#databases/seeds/posts_table_seeder.py 

from orator.seeds import Seeder

from app.Post import Post
from config.factories import factory

class PostsTableSeeder(Seeder):

    def run(self):
        """
        Run the database seeds.
        """
        
        factory(Post, 75).create()

To seed the database according to our blog objective, we must use the model Post. Normal. The factory method takes the Model we want to use and the numbers of entries we want to generate. Here, this will create 75 posts entrie each time we’ll run the seed command.

Register our migration in database_seeders.py

Registering the migration is quite simpe here.

#databases/seeds/database_seeder.py
"""Base Database Seeder Module."""

from orator.seeds import Seeder
from .user_table_seeder import UserTableSeeder

from .post_table_seeder import PostTableSeeder

class DatabaseSeeder(Seeder):

    def run(self):
        """Run the database seeds."""
        self.call(UserTableSeeder)
        
        self.call(PostTableSeeder)

Describe the seed file to Masonite in config/factories.py

Now that the seed file is registered, we must describe it to Masonite.

#config/factories.py

from orator.orm import Factory
from app.User import User

from app.Post import Post

factory = Factory()


def users_factory(faker):
    return {
        'name': faker.name(),
        'email': faker.email(),
        'password': '$2b$12$WMgb5Re1NqUr.uSRfQmPQeeGWudk/8/aNbVMpD1dR.Et83vfL8WAu',  # == 'secret'
    }

def posts_factory(faker):
    return{
        'author': faker.name(),
        'title': faker.name(),
        'description': faker.paragraph()
    }

factory.register(User, users_factory)
factory.register(Post, posts_factory)

We added a Post factory function and registered it at the end with factory.register(Post, posts_factory).

Setting up controller

We are going to use a Controller here to serve all the records from the databse.

craft controller 

This will create a file app/http/controllers/PostController.py.

"""A PostController Module."""

from masonite.request import Request
from masonite.view import View
from masonite.controllers import Controller

from app.Post import Post

class PostController(Controller):
    """PostController Controller Class."""

    def __init__(self, request: Request):
        """PostController Initializer

        Arguments:
            request {masonite.request.Request} -- The Masonite Request class.
        """
        self.request = request

    def show(self, view: View):
        return Post.all()

In show method, we added a line return Post.all() to retrieve all the entries. Now that we set up the Controller, we must specify a route with GET method to show the entries.

#routes/web.py
"""Web Routes."""

from masonite.routes import Get, Post

ROUTES = [
    Get('/', 'WelcomeController@show').name('welcome'),
    Get('/posts','PostController@show').name('posts')
]

The Entries!!!

Everything is done now. Let’s build it.

craft migrate

Output

[OK] Migrated 2018_01_09_043202_create_users_table
[OK] Migrated 2020_03_09_205230_create_posts_table

Now, we run the seeds.

craft seed:run Post

Output

Database seeded!

This done, run craft serve and hit http://127.0.0.1:8000/posts in your browser. You should see something like this.

And Voilà.

Conclusion

In this article, I showed you the concept of database seeding with Masonite. If you have any questions or recommendations, you are welcome in the comment section.