Use foreign keys for keeping the database clean

Published March 15, 2020 • 1 min read

When creating a migration it is a good habit to set foreign keys.

For example, if you have a 1:n relationship (hasMany and belongsTo) between the models "User" and "Articles", you would do the following:

In the user model:

public function articles()
{
    return $this->hasMany('App\Article');
}

In the article model:

public function user()
{
    return $this->belongsTo('App\User');
}

Example of a migration file:

Schema::create('articles', function(Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->string('title');
    $table->timestamps();


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

The onDelete('cascade') ensures that the articles belonging to the user are also deleted if the user himself is deleted.

laravel

Join my mailing list