dustbuster
dustbuster

Reputation: 82152

How do I drop a POSTGRES Table or a View in a laravel migration using eloquent?

I am aware that there's a question similar to this, with postgres, but that uses raw Sql, and I am looking for a laravel migration friendly ORM solution. That's why this question is different. This may in the long run be the right answer but I thought I'd pose it to the community.

Sometimes my data set is a table, sometimes it's view. If we are running the unit test build, this exists as a table, but everywhere else it's a view.

This is what I got. Obviously this is not idea. It's not an accurate conditional. While it may execute when I want it to, It's not a true check if a view exists. I want a way to check the postgres schema to see if a view exists.

if ('dev' === env('APP_ENV') || 'production' === env('APP_ENV')) {
    $sql = 'DROP VIEW IF EXISTS backend.friends';
    DB::statement($sql);   
} else {
    Schema::dropIfExists('backend.friends');
}

Mostly I need a conditional. Something like this. Any ideas good stack friends?

if (backed.friends) == view { 
    $sql = 'DROP VIEW IF EXISTS backend.partners'; 
} else {
    Schema::dropIfExists('backend.friends');
}

Thank you!

Upvotes: 2

Views: 712

Answers (1)

dustbuster
dustbuster

Reputation: 82152

The answer to this, is what Tim Lewis Suggested, staudenmeir/laravel-migration-views package. The way we use this is the following:

Since we already have the namespace class Schema in use by laravel, we need to alias it.

use Staudenmeir\LaravelMigrationViews\Facades\Schema as ViewSchema; Then you can perform conditionals and actions such as:

if (!empty($view) && ViewSchema::connection('<schema>')->hasView($view)) {
    ViewSchema::dropViewIfExists('<schema>.' . $view);
}

(replace <schema> to apply to your situation of course)

In our case, we are migrating from one schema to another and we need to be able to see if views exists otherwise create or drop them depending on the situation.

Basically everything you could do before on tables, now can be applied to views.

ViewSchema::connection('old_schema')->hasView('example')
ViewSchema::dropViewIfExists('old_schema.'.$exampleView);

Here's the repo, thank you staudenmeir for making this exist! https://github.com/staudenmeir/laravel-migration-views

I'm sure there's more functionality, but this is all we have needed thus far.

Upvotes: 2

Related Questions