Skip to content

Migrations and model

Marco E edited this page Sep 7, 2020 · 9 revisions

Defining Models

The easiest way to create a model instance is using the make:model Artisan command:

php artisan make:model Flight

If you would like to generate a database migration when you generate the model, you may use the --migration or -m option:

php artisan make:model Flight --migration
php artisan make:model Flight -m

Running migrations

To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

If you are using the Homestead virtual machine, you should run this command from within your virtual machine.

Table structure

To define the Many-to-many relationship, three database tables are needed: users, meetings, and meeting_user. The meeting_user table is derived from the alphabetical order of the related model names, and contains the user_id and meeting_id columns:

users
    id - integer
    name - string

meetings
    id - integer
    time - dateTime
    title - string
    description - text

meeting_user
    id - integer
    user_id - integer
    meeting_id - integer

Demo

  • Create the Meeting model and the migration files:
vagrant@meeting-api:~/code$ php artisan make:model Meeting -m
vagrant@meeting-api:~/code$ php artisan make:migration create_meeting_user_table
  • You do not need to modify the users migration file, use default.
  • Modify the meetings migration file as follow:
Schema::create('meetings', function (Blueprint $table) {
    $table->id();
    $table->timestamps();
    $table->dateTime('time');
    $table->string('title');
    $table->text('description');
});
  • Modify the meeting_user migration file as follow:
Schema::create('meeting_user', function (Blueprint $table) {
    $table->id();
    $table->timestamps();
    $table->integer('meeting_id');
    $table->integer('user_id');
});
  • Create the database tables:
vagrant@meeting-api:~/code$ php artisan migrate
Clone this wiki locally