Imagine you have a user who hasMany logs. If you delete the user, you probably don't need the logs of him anymore. The cleanest way to automatically remove them is to use foreign keys in your database. Note that the foreign key column needs to be unsigned.

Here is a clean code when you create a new database for a relation:

public function up()
  Schema::create('logs', function (Blueprint $table) {


If your relation already exists and may have some invalid references, you may add this at the top inside your up() function

  // Delete invalid references assuming that `belongsTo('App\User')`
  // method is created in logs and called `user`

If you do not want to remove the logs when you have removed the associated user, then the least one should do is to set the column `id_user` to null (make sure the column is set to nullable).

              ->onDelete('set null'); 

Foreign keys are automatically removed when the table is removed.

public function down()

However, if you just want to remove the column `id_user` you have to remove the foreign key first, otherwise you will get an foreign key restrain error.
The foreign key is always composed by "table name" + "field name" + "foreign. In this case:

public function down()
  Schema::table('logs', function (Blueprint $table) {


Leave a comment

Your email address will not be published. Required fields are marked *