Search code examples
mysqllaraveleloquentmodelforeign-keys

How can I know if a table column is a foreign key in Laravel through Model?


So as the title says, how can I know if a field of a Model is a foreign key in Laravel ?

Supose I have a FK column called show_type_id and a model named Event and I want to know if there is a function that given the model class or model table and the named field returns true if it is or false if is not.

...
$model = Event:class; // or Event::getTable();
$isFK = isFK('show_type_id', $model);
...

Edit

Thanks to @piscator this is what is worked:

use Illuminate\Support\Facades\Schema;

function isFK(string $table, string $column): bool
{
    $fkColumns = Schema::getConnection()
        ->getDoctrineSchemaManager()
        ->listTableForeignKeys($table);

    $fkColumns = collect($fkColumns);

    return $fkColumns->map->getColumns()->flatten()->search($column) !== FALSE;

}

Solution

  • Try this, assuming your table name is "events":

    Schema::getConnection()
        ->getDoctrineSchemaManager()
        ->listTableForeignKeys('events')
    

    This will return the Doctrine\DBAL\Schema\ForeignKeyConstraint object.

    With this data you could write the isFK method like this:

    use Illuminate\Support\Facades\Schema;
    
    function isFK(string $table, string $column): bool
    {  
        $fkColumns = Schema::getConnection()
            ->getDoctrineSchemaManager()
            ->listTableForeignKeys($table);
    
        return collect($fkColumns)->map(function ($fkColumn) {
            return $fkColumn->getColumns();
        })->flatten()->contains($column);
    }