hasib32
hasib32

Reputation: 835

Using Laravel schema builder and migrations

I am new to Laravel PHP framework. I am confused with how Laravel schema builder and migrations work. I created two tables using Laravel migrations. Below are my two tables:

public function up()
    {
        Schema::create('hotels', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('hotel_id');
            $table->string('name');
            $table->string('address')->nullable();
            $table->string('city')->nullable();
            $table->string('province')->nullable();
            $table->string('country')->nullable();
            $table->timestamps();
        });
    }

This is my other table:

public function up()
    {
        Schema::create('rooms', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('hotel_id');
            $table->string('name');
            $table->timestamps();
        });
    }

My question is how can can I make relations with two tables using Foreign keys? If I have to use Schema Builder where do I have to put the schema file?

Upvotes: 0

Views: 1261

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87739

You can do it in the very same migrations, using Schema Builder. This is how you create a foreign key using migrations:

public function up()
{
    Schema::create('rooms', function(Blueprint $table)
    {
        $table->increments('id');

        $table->integer('hotel_id');

        $table->string('name');

        $table->foreign('hotel_id')
              ->references('id')
              ->on('hotels')
              ->onDelete('cascade');

        $table->timestamps();
    });
}

Upvotes: 1

Related Questions