0

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?

1 Answer 1

1

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();
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

I am tried use your way. I am getting this errors: [Exception] SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'hotel_id' doesn't exist in table (SQL: alter table rooms add constraint rooms_hotel_id_foreign foreign key (hotel_id) references hotels (id) on delete cascade) (Bindings: array ( ))
so I have to create the column first then add the foreign key ?
Yes, but you can make it in the same migration. The foreign key is just a constraint + index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.