Home > Enterprise >  how to add exception in laravel migration?
how to add exception in laravel migration?

Time:09-15

I'm doing a migration and I want the execution of "artisan migrate" to stop until a field does not have the value 'CONTACT_INFO' inside.
What I want to do is an exception when I detect that this value is not there.

 public function up()
    {
        $emailConfiguration = EConfig::where('clave','CONTACTO_NAME')->get()->first();
        $eConfig = EConfig::find($emailConfiguration->pages_id);
        $Languages = Language::all();

        foreach ($Languages as $key => $lang) {
            $exists = !is_null($eConfig->pages_id);
            if ($exists) {
                $value = $eConfig->detail()->where('language_id', $lang->languages_id)->first()->pages_valor;
                if (strpos($value,'CONTACTO_INFO') == false) {
                    InvalidOrderException::reportable(function (InvalidOrderException $e) {
                        echo 'error';
                    });
                }
            }
        }
        
        
    }

CodePudding user response:

If I'm understanding your question correctly, you want to stop the migrations if a certain condition is not satisfied.

To do so, you need to throw the exception you want, for instance, with your code :

public function up()
{
        //... 

        foreach ($Languages as $key => $lang) {
            $exists = !is_null($eConfig->pages_id);
            
            if ($exists) {
                // ...
                if (strpos($value,'CONTACTO_INFO') == false) {
                    throw new \RuntimeException('Migration stopped due to invalid data');
                }
            }
        }    
}

However you may want to wrap it in a transaction to avoid any undesired behaviors

use Illuminate\Support\Facades\DB;

public function up()
{
  DB::transaction(function(){
          //... 

          foreach ($Languages as $key => $lang) {
              $exists = !is_null($eConfig->pages_id);
            
              if ($exists) {
                  // ...
                  if (strpos($value,'CONTACTO_INFO') == false) {
                      throw new \RuntimeException('Migration stopped due to invalid data');
                  }
              }
          }    
  }
});

If you want to customize your exception, you can create your own with php artisan make:exception MyMigrationCustomException

  • Related