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) {
          $table->integer('id_user')->unsigned();
          $table->string('log');
          $table->timestamps();

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

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`
  Logs::doesntHave('user')->delete(); 

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()
{
    Schema::dropIfExists('logs');
}  

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) {
          $table->dropForeign('logs_user_id_foreign');
          $table->dropColumn('user_id);

 });
}  
adam