DEV Community

Cover image for Laravel 7 short-cuts to writing foreign keys
wolfiton
wolfiton

Posted on

2 1

Laravel 7 short-cuts to writing foreign keys

Hi everyone,

Today I want to write about a quick tip to use when writing foreign keys in Laravel 7.

This method will help you write shorter migrations and make your code more readable.

For our example, I am going to use the user_id which is very common but this can be applied to any foreign key.

In the past we would write something like this:

$table->unsignedBigInteger('user_id')
->index();

$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');

Hmm, pretty verbose right?

The good news Dear reader is that we can write now like this:

$table->foreignId('user_id')
->index()
->constrained()
->onDelete('cascade');

Much nicer and easier to read, I hope you enjoyed this tip Dear Reader.

If you find it useful share it on social with your friends.

Have a nice day.

Credits:

Image cover: Long Road

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more