Postgres Range Type Support for Laravel 7


July 10th, 2020


The PosgreSQL range types package by @belamov provides range type support to Eloquent for the Postgres database:

Schema::create('table', function (Blueprint $table) {
    // ...
    // for int4range
    // for int8range

    // you can add any modifications
    // $table->dateRange('date_range')->nullable();
    // $table->dateRange('date_range')->default('[2010-01-01,2010-01-02)');

The main features of this package include:

  • Extended Laravel’s PostgresGrammar and PostgresConnection classes to provide a fluent API for range columns
  • Support for the following Postgres range types: daterange, tsrange, numrange, intrange, and timerange.
  • A number of query build macros for convenience (i.e., whereRangeContains($left, $right)
  • Model property casting

The model property casting provided by this package provides convenience for working with ranges on model instances. For example:

use Belamov\PostgresRange\Ranges\IntegerRange;

$range = new IntegerRange(10, 20, '[', ')');

$range->from(); // 10
$range->to(); // 20
(string) $range; // [10,20)
$range->forSql(); // '[10,20)'

You can learn more about this package, get full installation instructions, and view the source code on GitHub at belamov/postgres-range. The package has an excellent blog post to bring you up to speed on the powerful features available in Postgres’ range types: Ranges in Laravel 7 using PostgreSQL.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.