Laravel Database migrations Schema builder custom column type

1.6k Views Asked by At

I am trying to create migrations with Laravel but I am in a situation where I need custom column type since the one I want isn't included in schema builder , which is "POLYGON". So I want to know, how I can create my custom column type, other than those that are already in the Schema builder.

What I want would look like this in SQL statement:

alter table xxx add polygon POLYGON not null

Is it possible to do it by myself or I am forced to use some library like this?

I know that I can do like this:

DB::statement('ALTER TABLE country ADD COLUMN polygon POLYGON');

but it leads me to the error that the table doesn't exist.

2

There are 2 best solutions below

3
On

There is no built in way to do this but you can achieve a good result with minimal code.

<?php

use Illuminate\Database\Schema\Grammars\Grammar;

// Put this in a service provider's register function.
Grammar::macro('typePolygon', function (Fluent $column) {
    return 'POLYGON';
});
 
// This belongs in a migration.
Schema::create('my_table', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->addColumn('polygon', 'my_foo');
});

The key is to add a function with the name typePolygon to the Grammar class because this function is what determines the actual type used by the particular DBMS. We achieve this by adding a macro to the Grammar.

I have written a blog post about how to extend this solution to any custom type: https://hbgl.dev/add-columns-with-custom-types-in-laravel-migrations/

0
On

I assume you require spatial fields in your DB... I would consider via Packagist.org and search for laravel-geo (or equivalent) - which supports spatial column tyes inc Polygon. You could then use standard Laravel migration files for your custom fields -e.g.

$table->polygon('column_name');

In your UP function in your migration file...