Skip to content

Instantly share code, notes, and snippets.

@jwhulette
Last active May 28, 2023 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwhulette/dae05f50b96bb7b65c671b778b627fcf to your computer and use it in GitHub Desktop.
Save jwhulette/dae05f50b96bb7b65c671b778b627fcf to your computer and use it in GitHub Desktop.
[Check if foreign key exits] #php #laravel
<?php
declare(strict_types=1);
namespace Database\Helpers;
use Illuminate\Support\Facades\Schema;
class ForeignKey
{
public static function keyExists(string $table, string $foreignKey, ?string $database = null): bool
{
$keys = Schema::getConnection()->getDoctrineSchemaManager()->listTableForeignKeys($table, $database);
$foreign = collect($keys)->map(fn ($key) => $key->getName());
return $foreign->contains($foreignKey);
}
}
// create helper folder in database folder
// add "Database\\Helpers\\": "database/helpers/" to composer psr-4 section
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment