Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dineshsuthar92's avatar

How to check if mongo collection exists while migating in laravel 5.6?

I am using laravel 5.6, mongodb and mysql in one of my project. I used jessengers mongodb package and through which I created schema for my 3 collections, though mongodb is schema less database but for documentation purposes I created schema. one of the example is:

<?php

use Jenssegers\Mongodb\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateChatMessagesTable extends Migration
{

    /**
     * The name of the database connection to use.
     *
     * @var string
     */
    protected $connection = 'mongodb';


    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::connection($this->connection)->create('chat_messages', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('trade_id');
            $table->tinyInteger('type')->default('1');
            $table->text('content');
            $table->integer('recipient_id');
            $table->timestamp('recipient_read_at')->nullable();
            $table->timestamp('created_at')->nullable();
            $table->tinyInteger('status')->default('1');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::connection($this->connection)
            ->table('chat_messages', function (Blueprint $collection)
            {
                $collection->drop();
            });
    }
}

here the problem is whenever I run php artisan migrate:fresh command it gives me an error like collection already exists. I need to check, especially for mongodb, that if collection exists, then do not migrate the collection again.

I guessed that I should run a query like

if(true == ChatMessage::get()){
//do not run the migration
} else{
//continue the migration
}

in migration file only, but I never tried for this way, I kept it for last resolution. Please guide and help me.

0 likes
0 replies

Please or to participate in this conversation.