Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Yes, it is possible to determine if a table column is a foreign key using Laravel's Model. You can use the getConnection method to get the connection instance from the model and then use the getDoctrineSchemaManager method to get the schema manager instance. Finally, you can use the listTableForeignKeys method of the schema manager to get a list of foreign keys for the table, and check if the column in question is one of them. Here is an example code snippet:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class YourModel extends Model
{
    public function isForeignKey($column)
    {
        $connection = $this->getConnection();
        $schemaManager = $connection->getDoctrineSchemaManager();
        $table = $this->getTable();
        $foreignKeys = $schemaManager->listTableForeignKeys($table);

        foreach ($foreignKeys as $foreignKey) {
            $localColumns = $foreignKey->getLocalColumns();
            if (in_array($column, $localColumns)) {
                return true;
            }
        }

        return false;
    }
}

You can then call the isForeignKey method on an instance of your model and pass in the column name as a parameter to check if it is a foreign key. For example:

$model = new YourModel;
$isForeignKey = $model->isForeignKey('some_column');