1

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.

Tarvo Mäesepp
  • 4,477
  • 3
  • 44
  • 92

2 Answers2

4

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/

hBGl
  • 274
  • 2
  • 10
  • Grammar not working for me: Method Illuminate\Database\Schema\Grammars\PostgresGrammar::typeStatus does not exist. – Gilberto Albino Mar 14 '21 at 21:08
  • @hGBI on a brand new laravel 8 project I just created a migration to "my_table" and copied and pasted your code: https://gist.github.com/gilbertoalbino/d577db94057a98c653a72e0d638db31e – Gilberto Albino Mar 22 '21 at 11:43
  • @GilbertoAlbino I cannot reproduce the error on my side. I also created a new Laravel project, created a new migration, pasted your code, ran the migration, and it worked fine. If you ever find the cause of the problem, please let me know. – hBGl Mar 23 '21 at 05:54
0

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...

Jimmy
  • 242
  • 1
  • 3
  • 9