Tag Archives: php

Adding Foreign Key on Laravel 5.0

Published by:

To add a Foreign key on a migration Schema, First you have the create the table Schema and then alter the table to add the Foreign Key.

Here is an example.

A fund table do have user_id foreign link.This is done by adding following lines of code on create_funds_table.php
which was created by

php artisan make:migration create_funds_table --create=funds

On the php file created by above code, following editing should be done.

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFundsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('funds', function(Blueprint $table)
		{
			$table->increments('id')->unsigned();
			$table->integer('user_id')->unsigned();
			$table->float('amount');
			$table->timestamps();
			
		});
		Schema::table('funds', function(Blueprint $table)
		{
			$table->foreign('user_id')
				->references('id')
				->on('users')
				->onDelete('CASCADE')
				->onUpdate('CASCADE');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('funds');
	}

}

I had not explained in words so if you have any queries leave feedback. Thank you.