Model Relationships

Blueprint also allows you to define many of the relationships available within Laravel, including: belongsTo, hasOne, hasMany, and belongsToMany.

To define one of these relationships, you may add a relationships section to your model definition. Within this section, you specify the relationship type followed by a comma separated list of model names.

For example, the following definition adds some common relationships to a Post model:

    title: string:400
    published_at: timestamp nullable
      hasMany: Comment
      belongsToMany: Media, Site
      belongsTo: \Spatie\LaravelPermission\Models\Role

For each of these relationships, Blueprint will add the respective Eloquent relationship method within the generated model class. In addition, Blueprint will automatically generate the "pivot table" migration for any belongsToMany relationship.

To specify a model which is not part of your application, you may provide the fully qualified class name. Be sure to include the initial \ (backslash). For example, \Spatie\LaravelPermission\Models\Role.

You may also alias any of the relationships to give them a different name by suffixing the model name by appending the model name with a colon (:) followed by the name. For example:

      hasMany: Comment:reply

Blueprint will automatically pluralize the alias correctly based on the relationship type. In the case of a belongsToMany relationship, an alias will also be used as the pivot table name.

Sometimes you may want to use an intermediate model for a belongsToMany relationship. If so, you may prefix the alias with an ampersand (&) and reference the model name. For example:

    belongsToMany: Team:&Membership