1. Home
  2. Laravel
  3. Foreign key

Set a foreign key in the data base table. Makes a reference between tables using an id and a foreign key.

#laravel#db#migration
// Migration example
public function up(){
    Schema::create('subitems', function (Blueprint $table) {
        // Create all table fields
        $table->increments('id');
        $table->unsignedInteger('item_id');
        $table->string('text');
        $table->timestamps();
        
        // Set the foreign key
        $table->foreign('item_id')->references('id')->on('items');
        // Append the function below if you want to automatically remove all Subitems related to the Item
        // onDelete('cascade')
    });
}
copy
Full Laravel cheatsheet