Home /Laravel /Foreign Keys in laravel

Foreign Keys in laravel

Laravel also provides support for adding foreign key constraints to your tables:

$table->integer(‘user_id’)->unsigned();

$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)

In this example, we are stating that the user_id column references the id column on the users table. Make sure to create the foreign key column first!

<pre class=" language-php"><code class=" language-php"><span class="token variable">$table</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">foreign<span class="token punctuation">(</span></span><span class="token string">'user_id'</span><span class="token punctuation">)</span>
      <span class="token operator">-</span><span class="token operator">></span><span class="token function">references<span class="token punctuation">(</span></span><span class="token string">'id'</span><span class="token punctuation">)</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">on<span class="token punctuation">(</span></span><span class="token string">'users'</span><span class="token punctuation">)</span>
      <span class="token operator">-</span><span class="token operator">></span><span class="token function">onDelete<span class="token punctuation">(</span></span><span class="token string">'cascade'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>

Leave a Reply