Use Laravel's Illuminate Database abstraction in Contao

1.1.0 2019-08-19 12:49 UTC

This package is auto-updated.

Last update: 2024-02-24 06:14:06 UTC


Tests Version on packagist.org

Use Laravel's Illuminate Database abstraction in Contao with support for Contao models.


composer require loilo/contao-illuminate-database-bundle


Getting Started

Get the db() helper function:

use function Loilo\ContaoIlluminateDatabaseBundle\Database\db;

Calling the db() function creates a new Laravel query builder instance.

Basic Queries

This is how we'd fetch ID and name of the earliest admin of the Contao installation:

$row = db()
  ->select('id', 'name')
  ->where('admin', '1')

Note how the tl_ prefix is automatically prepended to table names, so we actually read from tl_user.

The above is just a very basic example. To get an idea of what's possible with this API, consult the Laravel docs.

Fetching Models

In addition to Laravel's built-in methods, the query builder of this package exposes an additional asModel() method.

Using it inside a query builder chain will instruct the get(), first(), find() and cursor() methods to return Contao models instead of plain database records.

To explain this based on the example above:

$user = db()
  ->asModel() // <- notice this line
  ->where('admin', '1')

// $user will be an instance of \UserModel

Customizing Connections

The db() function takes an optional argument which may override keys from the default connection configuration passed to Laravel's connection manager:

// Set an empty prefix to use the "tl_user" table
db([ 'prefix' => '' ])->from('tl_user')->first();