PHPackages                             tamedevelopers/database - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. tamedevelopers/database

ActiveComposer-plugin[Database &amp; ORM](/categories/database)

tamedevelopers/database
=======================

Lightweight PHP ORM Database Model.

6.0.14(5mo ago)61121[1 issues](https://github.com/tamedevelopers/database/issues)MITPHPPHP &gt;=8.0CI passing

Since May 3Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/tamedevelopers/database)[ Packagist](https://packagist.org/packages/tamedevelopers/database)[ Docs](https://github.com/tamedevelopers/database)[ RSS](/packages/tamedevelopers-database/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (60)Used By (0)

PHP ORM Database
================

[](#php-orm-database)

[![Total Downloads](https://camo.githubusercontent.com/33cfbe601fbdff735fe35ea2c0f00792e038d867ec503998b96c6214d6d54b49/68747470733a2f2f706f7365722e707567782e6f72672f74616d65646576656c6f706572732f64617461626173652f646f776e6c6f616473)](https://packagist.org/packages/tamedevelopers/database)[![Latest Stable Version](https://camo.githubusercontent.com/235e72296e8a00a53bb2048a37c18577f13aafa11d238280f30003fbdfe6ea44/68747470733a2f2f706f7365722e707567782e6f72672f74616d65646576656c6f706572732f64617461626173652f76657273696f6e2e706e67)](https://packagist.org/packages/tamedevelopers/database)[![License](https://camo.githubusercontent.com/163ab6cf336c8eaba828bdb6f37d11305d04bbe5fe32352901592e2242cdc161/68747470733a2f2f706f7365722e707567782e6f72672f74616d65646576656c6f706572732f64617461626173652f6c6963656e7365)](https://packagist.org/packages/tamedevelopers/database)[![Code Coverage](https://camo.githubusercontent.com/4dbcc37df594a0f88b6f02cbb6f460dd6c4a1febd84d6d3463e78f26dceeb3de/68747470733a2f2f636f6465636f762e696f2f67682f74616d65646576656c6f706572732f64617461626173652f6272616e63682f322e322e782f67726170682f62616467652e737667)](https://codecov.io/gh/tamedevelopers/database/branch/2.2.x)[![Gitter](https://camo.githubusercontent.com/a0f5d56a60f471ecd5ccc07e79273a036dd4db26f07b2e0eb4df77dfa83eb879/68747470733a2f2f6261646765732e6769747465722e696d2f74616d65646576656c6f706572732f64617461626173652e737667)](https://app.element.io/#/room/#php-orm-database:gitter.im)

Inspiration
-----------

[](#inspiration)

Having been introduced to learning Laravel Framework; Over the past yr(s), Coming back to vanilla PHP, was pretty tough. So i decided to create a much more easier way of communicating with Database, using native `PHP PDO:: Driver`.

Documentation
-------------

[](#documentation)

- [Requirements](#requirements)
- [Installation](#installation)
- [Instantiate](#instantiate)
- [Init php](#init-php)
- [Tame Cli](#tame-cli)
    - [Tame Cli Scaffold](#tame-cli-scaffold)
    - [Tame Cli DB](#tame-cli-db)
    - [Tame Cli Migrate](#tame-cli-migrate)
    - [Tame Cli Make](#tame-cli-make)
    - [Tame Cli Key](#tame-cli-key)
    - [Tame Artisan Call](#tame-artisan-call)
- [BootLoader](#bootLoader)
- [Database Connection](#database-connection)
- [Database Disconnect](#database-disconnect)
- [App Debug ENV](#app-debug-env)
- [Usage](#usage)
    - [table](#table)
    - [from](#from)
    - [insert](#insert)
    - [insertOrIgnore](#insert-or-ignore)
    - [update](#update)
    - [updateOrIgnore](#update-or-ignore)
    - [destroy](#destroy)
    - [delete](#delete)
    - [increment](#increment)
    - [decrement](#decrement)
    - [min](#min)
    - [max](#max)
    - [sum](#sum)
    - [avg](#avg)
    - [average](#average)
- [Database Connection Keys](#database-connection-keys)
- [Fetching Data](#fetching-data)
    - [get](#get)
    - [first](#first)
    - [firstOrCreate](#first-or-create)
    - [firstOrFail](#first-or-fail)
    - [count](#count)
    - [paginate](#paginate)
    - [exists](#exists)
    - [doesntExist](#doesntExist)
    - [tableExists](#table-exists)
- [Collections](#collections)
    - [Collection Methods](#collection-methods)
    - [Collection Usage](#collection-usage)
- [Auth](#auth)
    - [Auth Methods](#auth-methods)
    - [Auth Usage](#auth-usage)
    - [guard](#auth-guard)
    - [attempt](#auth-attempt)
    - [login](#auth-login)
    - [user](#auth-user)
    - [logout](#auth-logout)
    - [id](#auth-id)
- [Pagination](#pagination)
    - [Global Configuration](#global-configuration)
    - [Pagination Query](#pagination-query)
    - [Pagination Data](#pagination-data)
    - [Pagination Links](#pagination-links)
    - [Pagination Links Config](#pagination-links-config)
    - [Pagination Showing](#pagination-showing)
    - [Pagination Showing Config](#pagination-showing-config)
    - [Pagination Foreach Numbers](#pagination-foreach-numbers)
    - [Pagination Ajax Loading](#pagination-ajax-loading)
    - [Get Pagination](#get-pagination)
- [Clause](#clause)
    - [query](#query)
    - [select](#select)
    - [selectRaw](#selectRaw)
    - [orderBy](#orderby)
    - [orderByRaw](#orderbyraw)
    - [orderByDesc](#orderByDesc)
    - [orderByAsc](#orderByAsc)
    - [latest](#latest)
    - [oldest](#oldest)
    - [inRandomOrder](#inRandomOrder)
    - [random](#random)
    - [limit](#limit)
    - [take](#take)
    - [offset](#offset)
    - [join](#join)
    - [joinWhere](#joinWhere)
    - [leftJoin](#leftJoin)
    - [leftJoinWhere](#leftJoinWhere)
    - [rightJoin](#rightJoin)
    - [rightJoinWhere](#rightJoinWhere)
    - [crossJoin](#crossJoin)
    - [where](#where)
    - [orWhere](#orwhere)
    - [whereNot](#whereNot)
    - [orWhereNot](#orWhereNot)
    - [whereRaw](#whereRaw)
    - [whereColumn](#wherecolumn)
    - [orWhereColumn](#orWhereColumn)
    - [whereNull](#wherenull)
    - [orWhereNull](#orWhereNull)
    - [whereNotNull](#wherenotnull)
    - [orWhereNotNull](#orWhereNotNull)
    - [whereBetween](#wherebetween)
    - [orWhereBetween](#orWhereBetween)
    - [whereNotBetween](#wherenotbetween)
    - [orWhereNotBetween](#orWhereNotBetween)
    - [whereBetweenColumns](#whereBetweenColumns)
    - [orWhereBetweenColumns](#orWhereBetweenColumns)
    - [whereNotBetweenColumns](#whereNotBetweenColumns)
    - [orWhereNotBetweenColumns](#orWhereNotBetweenColumns)
    - [whereDate](#whereDate)
    - [orWhereDate](#orWhereDate)
    - [whereTime](#whereTime)
    - [orWhereTime](#orWhereTime)
    - [whereDay](#whereDay)
    - [orWhereDay](#orWhereDay)
    - [whereMonth](#whereMonth)
    - [orWhereMonth](#orWhereMonth)
    - [whereYear](#whereYear)
    - [orWhereYear](#orWhereYear)
    - [having](#having)
    - [orHaving](#orHaving)
    - [havingNull](#havingNull)
    - [orHavingNull](#orHavingNull)
    - [havingNotNull](#havingNotNull)
    - [orHavingNotNull](#orHavingNotNull)
    - [havingBetween](#havingBetween)
    - [havingRaw](#havingRaw)
    - [whereIn](#wherein)
    - [orWhereIn](#orWhereIn)
    - [whereNotIn](#wherenotin)
    - [orWhereNotIn](#orWhereNotIn)
    - [orHavingRaw](#orHavingRaw)
    - [groupBy](#groupby)
    - [groupByRaw](#groupByRaw)
- [Database Migration](#database-migration)
    - [Create Table Schema](#create-table-schema)
    - [Default String Length](#default-string-length)
    - [Update Column Default Value](#update-column-default-value)
    - [Run Migration](#run-migration)
    - [Drop Migration](#drop-migration)
    - [dropTable](#drop-table)
    - [dropColumn](#drop-column)
- [Get Database Config](#get-database-config)
- [Get Database Connection](#get-database-connection)
- [Get Database Name](#get-database-name)
- [Get Database PDO](#get-database-pdo)
- [Get Database TablePrefix](#get-database-tableprefix)
- [Database Import](#database-import)
- [Update Env Variable](#update-env-variable)
- [Autoload Register](#autoload-register)
- [Collation And Charset](#collation-and-charset)
- [Extend Model Class](#extend-model-class)
- [Helpers Functions](#helpers-functions)
- [Error Dump](#error-dump)
- [Error Status](#error-status)
- [Useful links](#useful-links)

Requirements
------------

[](#requirements)

- `>= php 8.0+`

Installation
------------

[](#installation)

Prior to installing `database package` get the [Composer](https://getcomposer.org) dependency manager for PHP because it'll simplify installation.

```
composer require tamedevelopers/database

```

Instantiate
-----------

[](#instantiate)

**Step 1** — `Require composer autoload`:

```
require_once __DIR__ . '/vendor/autoload.php';
```

**Step 2** — \[optional\] `If you want the Package scalfolding`

- This will auto setup your entire application on a `go!`
    - It's helper class can be called, using -- `autoloader_start()`

DescriptionIt's important to install vendor in your project root, As we use this to get your root \[dir\]By default you don't need to define any path againFiles you'll see after you reload browser:`.env` `.env.example` `.gitignore` `.htaccess` `.user.ini` `init.php````
use Tamedevelopers\Database\AutoLoader;

AutoLoader::start();
// then reload your browser to allow the system scalfold for you
```

init php
--------

[](#init-php)

- \[optional\] This will extends the `composer autoload` and other setup
    - If you used the package `Package scalfolding` this file will be automatically generated, that you can include at the beginning of your project.

Tame Cli
--------

[](#tame-cli)

- Custom commands support for CLI

```
php tame list
```

### tame-cli-scaffold

[](#tame-cli-scaffold)

- Scalffold the database files, instead of running `AutoLoader::start()` in browser.
    - The `-f|--force` flag is needed if you're inside a framework or if on production server.
    - This doesn't alter nor replace any files that exists and safe.

```
php tame scaffold:run --force
```

### tame-artisan-call

[](#tame-artisan-call)

- Using the CLI from within php, without the CMD interface.

```
use Tamedevelopers\Support\Capsule\Artisan;

Artisan::call('db:wipe --force');
```

BootLoader
----------

[](#bootloader)

- \[optional\] from `version ^6.0.3` If you do not want to include or use the `init.php` file
    - You can as well call the bootloader, to start the database life-circle.

```
use Tamedevelopers\Database\Capsule\AppManager;

AppManager::bootLoader();
// app_manager()->bootLoader();
```

Database Connection
-------------------

[](#database-connection)

- Take two param as `[$name|$options]`
    - Mandatory `$name` as string of connection name
    - \[optional\] `$options` and an array, if no connection data is found
    - First navigate to \[config/database.php\] file and add connection configuration or use .env

```
DB::connection('connName', $options);
```

Database Disconnect
-------------------

[](#database-disconnect)

- If you want to connect to already connected database, You first need to disconnect
    - Takes one param as `string`

```
DB::disconnect('connName');
```

Database Reconnect
------------------

[](#database-reconnect)

- same as `Database Connection`

```
DB::reconnect('connName', $options);
```

App Debug Env
-------------

[](#app-debug-env)

- The `.env` file contains a key called `APP_DEBUG`
    - It's mandatory to set to false on Production environment
    - This helps to secure your applicaiton and exit with error 404
    - instead of displaying entire server errors.

keyTypeDefault ValueAPP\_DEBUGboolean`true`Database Connection Keys
------------------------

[](#database-connection-keys)

- All available connection keys
    - The DB\_CONNECTION uses only `mysql`
    - No other connection type is supported for now.

keyTypeDefault Valuedriverstring`mysql`hoststring`localhost`portint`3306`databasestringusernamestringpasswordstringcharsetstring`utf8mb4`collationstring`utf8mb4_unicode_ci`prefixstringprefix\_indexesbool`false`Usage
-----

[](#usage)

- All Methods of usage
    - Without calling the `DB::connection()` and passing the driver name you want. It will automatically be using the default connection driver, you've in your setup'

### Table

[](#table)

- Takes a parameter as `string` table\_name

```
$db = DB::connection();

$db->table('users');
```

### Insert

[](#insert)

- Takes one parameter as assoc array `column_name => value`
    - It returns an object on success or error

```
DB::table('users')->insert([
    'user_id'    => 10000001,
    'first_name' => 'Alfred',
    'last_name'  => 'Pete',
    'wallet_bal' => 0.00,
    'registered' => strtotime('now'),
]);

-- To see data, you need to save into a variable
```

### Insert Or Ignore

[](#insert-or-ignore)

- Same as `insert()` method
    - It returns an object of created data or `false` on error

```
DB::table('users')->insertOrIgnore([
    'user_id'    => 10000001,
    'first_name' => 'Alfred',
]);
```

### Update

[](#update)

- Takes one parameter as assoc array `column_name => value`
    - Returns an `int` numbers of affected rows or error

```
DB::table('users')
    ->where('user_id', 10000001)
    ->update([
        'first_name' => 'Alfred C.',
    ]);
```

### Update Or Ignore

[](#update-or-ignore)

- Same as `update()` method
    - Returns an `int` numbers of affected rows or `0` on error

```
DB::table('users')
    ->where('user_id', 10000001)
    ->updateOrIgnore([
        'first_name' => 'Alfred C.',
    ]);
```

### delete

[](#delete)

- Returns an `int`

```
DB::table('users')
    ->where('user_id', 10000001)
    ->delete();
```

### destroy

[](#destroy)

- Take two param as `[value|column]`
    - Mandatory `value` as mixed value
    - \[optional\] `column` as Default is `id`
    - Returns an `int`

```
DB::table('posts')->destroy(1);
// Query: delete from `posts` where `id` = ?

DB::table('posts')->destroy(10, 'post_id');
// Query: delete from `posts` where `post_id` = ?

```

### Increment

[](#increment)

- Takes three parameter
    - Only the first param is required

paramData typescolumn `required`string`count or []`int | arrayparamarray1 By default if the the second param not passed, this will increment by 1

```
DB::table('users')
    ->where('user_id', 10000001)
    ->increment('wallet_bal');
```

```
DB::table('users')
    ->where('user_id', 10000001)
    ->increment('wallet_bal', 10);
```

- You can also pass in a second or third parameter to update additional columns

```
DB::table('users')
    ->where('user_id', 10000001)
    ->increment('wallet_bal', 100.23, [
        'first_name' => 'F. Peterson',
        'status'     => 1,
    ]);
```

- You can ommit the second param and it'll be automatically seen as update param (If an array)

```
DB::table('users')
    ->where('user_id', 10000001)
    ->increment('wallet_bal', [
        'first_name' => 'F. Peterson',
        'status'     => 1,
    ]);
```

### Decrement

[](#decrement)

- Same as Increment

```
DB::table('users')
    ->where('user_id', 10000001)
    ->decrement('wallet_bal', [
        'first_name' => 'F. Peterson',
        'status'     => 1,
    ]);
```

### min

[](#min)

- Take one param as `Expression|string`

```
DB::table('blog')->min('amount');
```

### max

[](#max)

- Same as min

```
DB::table('blog')->max('amount');
```

### sum

[](#sum)

- Take one param as `Expression|string`

```
DB::table('blog')->sum('amount');
```

### avg

[](#avg)

- Take one param as `Expression|string`

```
DB::table('blog')->avg('amount');
DB::table('blog')->average('amount');
```

Fetching Data
-------------

[](#fetching-data)

object nameReturnsget()array of objectsfind()`object` | `null`first()`object` | `null`FirstOrIgnore()`object` | `null`FirstOrCreate()objectfirstOrFail()object or exit with 404 statuscount()intpaginate()array of objectsexists()boolean `true` | `false`tableExists()boolean `true` | `false`### GET

[](#get)

```
DB::table('users')->get();
```

### First

[](#first)

```
DB::table('users')->first();
```

### First or Create

[](#first-or-create)

- Take two param as an `array`

    - Mandatory `$conditions` param as `array`
    - \[optional\] `$data` param as `array`
- First it checks if codition to retrieve data. If fails, then it merge the `$conditions` to `$data` value to create new records

```
DB::table('users')->firstOrCreate(
    ['email' => 'example.com']
);
```

- or -- `Example 2`

```
DB::table('users')->firstOrCreate(
    ['email' => 'example.com'],
    [
        'country'   => 'Nigeria',
        'age'       => 18,
        'dob'       => 2001,
    ]
);
```

### First or Fail

[](#first-or-fail)

- Same as `first()` method but exit with error code 404, if data not found

```
DB::table('users')->firstOrFail();
```

### Count

[](#count)

```
DB::table('users')->count();
```

### Paginate

[](#paginate)

- Takes param as `int` `$per_page`
    - By default if no param is given, then it displays 10 per page

```
$users = DB::table('users')
            ->paginate(40);

$users // this will return the data objects
$users->links() // this will return the paginations links view
$users->showing() // Display items of total results
```

### Exists

[](#exists)

- Returns boolean `true \| false`

```
DB::table('users')
    ->where('email', 'email@gmail.com')
    ->orWhere('name', 'Mandison')
    ->exists();
```

### Table Exists

[](#table-exists)

- Takes param as `string` `$table_name`

```
DB::tableExists('users');
```

Collections
-----------

[](#collections)

- You can directly use `methods` of `Collections Instance` on any of the below
- All the below `methods` are received by Collection `class`
    1. get()
    2. find()
    3. first()
    4. firstOrIgnore()
    5. firstOrCreate()
    6. firstOrFail()
    7. insert()
    8. insertOrIgnore()

### Collection Methods

[](#collection-methods)

MethodsDescriptiongetAttributes()`array` Returns an array of datagetOriginal()`object` Returns an object of dataisEmpty()`boolean` `true | false` If data is emptyisNotEmpty()`opposite` of `->isEmpty()`count()`int` count data in items collectiontoArray()`array` Convert items to arraytoObject()`object` Convert items to objecttoJson()`string` Convert items to json### Collection Usage

[](#collection-usage)

- Colections are called automatically on all Database Fetch Request
    - With this you can access data as an `object\|array` key property
    - If no data found then it returns null on `->first()` method only

```
$user = DB::tableExists('users')
            ->first();

if($user){
    $user->first_name
    $user['first_name']
}

$user->toArray()
$user->getAttributes()
```

- Example two(2) `->get() \| ->paginate()` Request

```
$users = DB::tableExists('users')
            ->where('is_active', 1),
            ->random(),
            ->get();

if($users->isNotEmpty()){
    foreach($users as $user){
        $user->first_name
        $user['first_name']
        $user->toArray()
        $user->getAttributes()
    }
}
```

Auth
----

[](#auth)

- Lightweight guard-based authentication similar to Laravel.
- attempt() only validates and sets in-memory user; call login() to persist to session.

method nameDescriptionguard()Create a guard bound to a table and \[optional\] connection.attempt()Validate credentials, set in-memory user on success; does not persist to session.login()Persist the current user (or provided array) to session. If userData is not an array, it’s ignored.user()Get the in-memory user or rehydrate from session if available.id()Get the authenticated user’s id (or custom key).logout()Clear in-memory user and remove from session.### auth-guard

[](#auth-guard)

- Set the authentication guard (Takes two param)
    - Mandatory `$table` param as `string`
    - \[optional\] `$connection` param as `string | null` database connection name.

```
use Tamedevelopers\Database\Auth;

$admin = Auth::guard('admins');
```

### Auth Usage

[](#auth-usage)

```
use Tamedevelopers\Database\Auth;

// Create guards
$admin = (new Auth)->guard('tb_admin');
$user  = (new Auth)->guard('tb_user', 'woocommerce');

// Credentials (password is required in attempt)
$credentials = [
    'email' => 'peter.blosom@gmail.com',
    'status' => '1',
    'password' => 'tagged',
];

// 1) Validate credentials only (no session persistence)
if ($user->attempt($credentials)) {
    // In-memory user available
    $user->check();          // true
    $user->id();             // e.g., 123
    $user->user();           // full user array
}

// 2) Persist explicitly (similar to Laravel Auth::login())
$user->login($user->user());   // stores sanitized user in session (no password)

// 3) Retrieve later in another request
$another = (new Auth)->guard('tb_user', 'woocommerce');
$another->user();    // rehydrated from session
$another->check();   // true if session had user

// 4) Logout
$another->logout();  // clears in-memory and session
```

Pagination
----------

[](#pagination)

- Configuring Pagination
    - It's helper class can be called, using -- `config_pagination()`

keyData TypeDescriptionallow`true` | `false`Default `false` Setting to true will allow the system use this settings across appclassstringCss `selector` For pagination ul tag in the browserspanstringDefault `.page-span` Css `selector` For pagination Showing Span tags in the browserview`bootstrap` | `cursor` | `loading` | `onloading`Default `simple` - For pagination designfirststringChange the letter `First`laststringChange the letter `Last`nextstringChange the letter `Next`prevstringChange the letter `Prev`showingstringChange the letter `Showing`ofstringChange the letter `of`resultsstringChange the letter `results`buttonsintNumbers of pagination links to generate. Default is 5 and limit is 20### Global Configuration

[](#global-configuration)

- 1 Setup global pagination on ENV autostart `most preferred` method

```
AutoLoader::configPagination([
    'allow' => true,
    'prev'  => 'Prev Page',
    'last'  => 'Last Page',
    'next'  => 'Next Page',
    'view'  => 'bootstrap',
    'class' => 'Custom-Class-Css-Selector',
]);
```

### Pagination Query

[](#pagination-query)

```
$users = DB::table('users')->paginate(40);
```

### Pagination Data

[](#pagination-data)

```
$users
// This will return `Collections` of pagination data
```

### Pagination Links

[](#pagination-links)

```
$users->links();
// This will return pagination links view
```

### Pagination Links Config

[](#pagination-links-config)

Read more...- You can directly configure pagination links
    - It'll override the global settings

```
$users->links([
    'first' => 'First Page',
    'last'  => 'Last Page',
    'prev'  => 'Previous Page',
    'next'  => 'Next Page',
    'no_content'  => 'All videos has been loaded',
])
```

### Pagination Showing

[](#pagination-showing)

```
$users->showing();

// This will create a span html element with text

    Showing 0-40 of 500 results

```

### Pagination Showing Config

[](#pagination-showing-config)

Read more...- You can configure showing text directly as well

```
$users->showing([
    'showing'  => 'Showing',
    'of'       => 'out of',
    'results'  => 'Results',
    'span'     => 'css-selector',
])
```

### Pagination Foreach Numbers

[](#pagination-foreach-numbers)

- Page numbering `starts counting from 1`
    - This will format all pagination items collections
    - On each page, it starts counting from last pagination item number

```
$users = DB::table('users')->paginate(20);

foreach($users as $user){
    echo $user->numbers();
}
```

### Pagination Ajax Loading

[](#pagination-ajax-loading)

- When the view is either `loading|` | `onloading` | `cursor` | `bootstrap`
    - This can automatically fetched data without page load
    - You need to give your DOM-element `data-pagination-content` and `data-pagination-append`

```
$users = DB::table('users')->paginate(20);
```

```

or

    links([
        'no_content' => 'All users have been loaded.'
    ]); ?>

```

### Get Pagination

[](#get-pagination)

- Returns pagination informations

keyDescriptionlimitPagination limit `int`offsetPagination offset `int`pagePagination Current page `int`pageCountPagination Total page count `int`perPagePagination per page count `int`totalCountPagination total items count `int````
$users = DB::table('users')->paginate(20);

$users->getPagination();
```

Clause
------

[](#clause)

- Multiple clause

### Query

[](#query)

- Allows the use direct sql query `SQL query syntax`
    - Or direct query exec()
    - \[important\] you cannot use paginate on `query()` method

```
DB::query("SHOW COLUMNS FROM users")
    ->limit(10)
    ->get();

DB::query("ALTER TABLE `langs` ADD COLUMN es TEXT; UPDATE `langs` SET es = en;")
    ->exec();
```

### Select

[](#select)

- Used to select needed columns from database

```
DB::table('users')
    ->where('user_id', 10000001)
    ->select(['first_name', 'email'])
    ->select('email', 'name')
    ->first();
```

### orderBy

[](#orderby)

- Takes two param `$column` and `$direction`
    - By default `$direction` param is set to `ASC`

```
DB::table('wallet')
    ->orderBy('date', 'DESC')
    ->get();
```

### orderByRaw

[](#orderbyraw)

- Takes one param `$query`

```
DB::table('wallet')
    ->orderByRaw('CAST(`amount` AS UNSIGNED) DESC')
    ->get();
```

### Latest

[](#latest)

- Takes one param `$column` by default the column used is `id`

```
DB::table('wallet')
    ->latest('date')
    ->get();
```

### Oldest

[](#oldest)

- Takes one param `$column` by default the column used is `id`

```
DB::table('wallet')
    ->oldest()
    ->get();
```

### inRandomOrder

[](#inrandomorder)

```
DB::table('wallet')
    ->inRandomOrder()
    ->get();
```

### random

[](#random)

Read more...- Same as `inRandomOrder()`

```
DB::table('wallet')
    ->random()
    ->get();
```

### limit

[](#limit)

- Takes one param `$limit` as int. By default value is `1`

```
DB::table('wallet')
    ->limit(10)
    ->get();
```

### offset

[](#offset)

Read more...- Takes one param `$offset` as int. By default value is `0`

```
DB::table('wallet')
    ->limit(3)
    ->offset(2)
    ->get();
```

- Example 2 (Providing only offset will return as LIMIT without error)

```
DB::table('wallet')
    ->offset(2)
    ->get();
```

### join

[](#join)

- Includes `join`|`leftJoin`|`rightJoin`|`crossJoin`

ParamsDescriptiontabletableforeignColumntable.columnoperatoroperator signlocalColumnlocal\_table.column```
DB::table('wallet')
    ->join('users', 'users.user_id', '=', 'wallet.user_id')
    ->get();
```

- or

```
DB::table('wallet')
    ->join('users', 'users.user_id', '=', 'wallet.user_id')
    ->where('wallet.email', 'example.com')
    ->orWhere('wallet.user_id', 10000001)
    ->paginate(10);
```

### leftJoin

[](#leftjoin)

- Same as `join`

```
DB::table('wallet')
    ->leftJoin('users', 'users.user_id', '=', 'wallet.user_id')
    ->where('wallet.email', 'example.com')
    ->get();
```

### where

[](#where)

- Takes three parameter
    - Only the first param is required

paramData typescolumnstringoperatorstringvaluestring```
DB::table('wallet')
    ->where('user_id', 10000001)
    ->where('amount', '>', 10)
    ->where('balance', '>=', 100)
    ->get();
```

### orWhere

[](#orwhere)

Read more...- Same as Where clause

```
DB::table('wallet')
    ->where('user_id', 10000001)
    ->where('amount', '>', 10)
    ->orWhere('first_name', 'like', '%Peterson%')
    ->where('amount', 'where('user_id', 10000001)
    ->whereBetween('amount', [0, 100])
    ->get();
```

### whereNotBetween

[](#wherenotbetween)

Read more...- Same as `whereBetween()` method

```
DB::table('wallet')
    ->where('user_id', 10000001)
    ->whereNotBetween('amount', [0, 100])
    ->get();
```

### whereIn

[](#wherein)

- Takes two parameter `column` as string `param` as array
    - Doesn't support float value

paramData typesValuecolumnstring`column_name`paramarray\[0, 20, 80\]```
DB::table('wallet')
    ->where('user_id', 10000001)
    ->whereIn('amount', [10, 20, 40, 100])
    ->get();
```

### whereNotIn

[](#wherenotin)

Read more...Same as `whereIn()` method

```
DB::table('wallet')
    ->where('user_id', 10000001)
    ->whereNotIn('amount', [10, 20, 40, 100])
    ->get();
```

### groupBy

[](#groupby)

- Takes one param `$column`

```
DB::table('wallet')
    ->where('user_id', 10000001)
    ->groupBy('amount')
    ->get();
```

Database Migration
------------------

[](#database-migration)

- Similar to Laravel DB Migration `Just to make database table creation more easier`

method nameReturnscreate()Create table schemarun()Begin migrationdrop()Drop migration tables```
use Tamedevelopers\Database\Migrations\Migration;
```

### Create Table Schema

[](#create-table-schema)

- Takes param as string `$table`
    - \[optional\] Second parameter `string` `jobs|sessions` If passed will create a dummy `jobs|sessions` table schema
    - It's helper class can be called, using -- `migration()`

```
Migration::create('users');
Migration::create('users_wallet');
Migration::create('tb_jobs', 'jobs');
Migration::create('tb_sessions', 'sessions');
// migration()->create('users');

// Table `2023_04_19_1681860618_user` has been created successfully
// Table `2023_04_19_1681860618_user_wallet` has been created successfully
// Table `2023_04_19_1681860618_tb_jobs` has been created successfully
// Table `2023_04_19_1681860618_tb_sessions` has been created successfully
```

[![Sample Session Schema](https://raw.githubusercontent.com/tamedevelopers/UltimateOrmDatabase/main/sessions.png)](https://raw.githubusercontent.com/tamedevelopers/UltimateOrmDatabase/main/sessions.png)

### Default String Length

[](#default-string-length)

- In some cases you may want to setup default string legnth to all Migration Tables
    - It's helper class can be called, using -- `schema()`

DescriptionThe Default Set is `255` But you can override by setting custom valueAccording to MySql v:5.0.0 Maximum allowed legnth is `4096` charsIf provided length is more than that, then we'll revert to default as the aboveThis affects only `VACHAR`You must define this before start using the migrations```
use Tamedevelopers\Database\Migrations\Schema;

Schema::defaultStringLength(200);
// schema()->defaultStringLength(2000);
```

### Update Column Default Value

[](#update-column-default-value)

- In some cases you may want to update the default column value
    - Yes! It's very much possible with the help of Schema. Takes three (3) params
    - `$tablename` as string
    - `$column_name` as string
    - `$values` as mixed data `NULL` `NOT NULL\|None` `STRING` `current_timestamp()`

```
use Tamedevelopers\Database\Migrations\Schema;

Schema::updateColumnDefaultValue('users_table', 'email_column', 'NOT NULL');
Schema::updateColumnDefaultValue('users_table', 'gender_column', []);

// or
// schema()->updateColumnDefaultValue('users_table', 'gender_column', []);
```

### Run Migration

[](#run-migration)

- This will execute and run migrations using files located at \[root/database/migrations\]

```
Migration::run();

or
migration()->run();

// Migration runned successfully on `2023_04_19_1681860618_user`
// Migration runned successfully on `2023_04_19_1681860618_user_wallet`
```

### Drop Migration

[](#drop-migration)

Read more...- Be careful as this will execute and drop all files table `located in the migration`
- \[optional param\] `bool` to force delete of tables

```
Migration::drop();

or
migration()->drop(true);
```

### Drop Table

[](#drop-table)

Read more...- Takes one param as `string` $table\_name

```
use Tamedevelopers\Database\Migrations\Schema;

Schema::dropTable('table_name');

or
schema()->dropTable('table_name');
```

### Drop Column

[](#drop-column)

Read more...- To Drop Column `takes two param`
    - This will drop the column available

```
use Tamedevelopers\Database\Migrations\Schema;

Schema::dropColumn('table_name', 'column_name');

or
schema()->dropColumn('table_name', 'column_name');
```

Get Database Config
-------------------

[](#get-database-config)

```
$db->getConfig()
```

Get Database Connection
-----------------------

[](#get-database-connection)

- It's helper class can be called, using -- `db_connection()`

```
$db->dbConnection()
```

Get Database Name
-----------------

[](#get-database-name)

```
$db->getDatabaseName()
```

Get Database PDO
----------------

[](#get-database-pdo)

```
$db->getPDO()
```

Get Database TablePrefix
------------------------

[](#get-database-tableprefix)

```
$db->getTablePrefix()
```

Database Import
---------------

[](#database-import)

- You can use this class to import `.sql` into a database programatically
    - Take two param as `[$path|$connection]`
    - Mandatory `$path` as string of path to .sql file
    - \[optional\] `$connection` define the connection of database you want to run

```
use Tamedevelopers\Database\DBImport;

$database = new DBImport('path_to/orm.sql', 'connName');
// new DBImport(base_path('path_to/orm.sql'))

// run the method
$status = $database->run();

// - Status code
// ->status == 404 (Failed to read file or File does'nt exists
// ->status == 400 (Query to database error
// ->status == 200 (Success importing to database
```

Update Env Variable
-------------------

[](#update-env-variable)

- You can use this class to import .sql into a database programatically

ParamsDescriptionkeyENV keyvalueENV valueallow\_quote`true` | `false` - Default is true (Allow quotes within value)allow\_space`true` | `false` - Default is false (Allow space between key and value)```
use Tamedevelopers\Support\Env;

Env::updateENV('DB_PASSWORD', 'newPassword');
Env::updateENV('APP_DEBUG', false);
Env::updateENV('DB_CHARSET', 'utf8', false);

// env_update('DB_CHARSET', 'utf8', false);
// Returns - Boolean
// true|false
```

Collation And Charset
---------------------

[](#collation-and-charset)

- Collation and Charset Data `listing`

### Collation

[](#collation)

- utf8\_bin
- utf8\_general\_ci
- utf8mb4\_bin
- utf8mb4\_unicode\_ci
- utf8mb4\_general\_ci
- latin1\_bin
- latin1\_general\_ci

### Charset

[](#charset)

- utf8
- utf8mb4
- latin1

Extend Model Class
------------------

[](#extend-model-class)

Read more...- You can as well extends the DB Model class directly from other class

```
use Tamedevelopers\Database\Model;

class Post extends Model{

    // define your custom model table name
    protected $table = 'posts';

    // -- You now have access to the DB public instances
    public function getPost(){
        return $this->select(['images', 'title', 'description'])->get();
    }
}
```

Helpers Functions
-----------------

[](#helpers-functions)

function nameDescriptiondb()Return instance of `new DB($options)` classdb\_connection()Same as `$db->dbConnection()`config\_pagination()Same as `$db->configPagination()` or `AutoLoader::configPagination`autoloader\_start()Same as `AutoLoader::start()`env\_update()Same as `Env::updateENV` methodapp\_manager()Return instance of `(new AppManager)` classimport()Return instance of `(new DBImport)->import()` methodmigration()Return instance of `(new Migration)` classschema()Return instance of `(new Schema)` classError Dump
----------

[](#error-dump)

functionDescriptiondumpDump DataddDump and DieError Status
------------

[](#error-status)

- On error returns `404` status code
- On success returns `200` status code

Useful Links
------------

[](#useful-links)

- @author Fredrick Peterson (Tame Developers)
- If you love this PHP Library, you can [Buy Tame Developers a coffee](https://www.buymeacoffee.com/tamedevelopers)
- [Lightweight - PHP ORM Database](https://github.com/tamedevelopers/database)
- [Support - Library](https://github.com/tamedevelopers/support)

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance68

Regular maintenance activity

Popularity16

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~16 days

Total

59

Last Release

165d ago

Major Versions

1.0.5 → 2.1.12023-05-03

2.2.9 → 3.0.12023-05-05

3.1.9 → 4.0.12023-05-20

4.3.9 → 5.0.02023-10-07

5.0.10 → 6.0.12025-04-22

PHP version history (3 changes)1.0.5PHP &gt;=7.2

4.2.0PHP &gt;=7.2.5

4.3.8PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/d363c130739125512fda1ddbac6287f43d4eac8bd96808d44cdd525737c16486?d=identicon)[tamedevelopers](/maintainers/tamedevelopers)

---

Top Contributors

[![tamedevelopers](https://avatars.githubusercontent.com/u/52910237?v=4)](https://github.com/tamedevelopers "tamedevelopers (114 commits)")

---

Tags

databaseormorm-libraryorm-modelphpphp-orm-pdophp-databaseorm databasephp orm databasephp orm github

### Embed Badge

![Health badge](/badges/tamedevelopers-database/health.svg)

```
[![Health](https://phpackages.com/badges/tamedevelopers-database/health.svg)](https://phpackages.com/packages/tamedevelopers-database)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[orchestra/database

Database Component for Orchestra Platform

201.4M578](/packages/orchestra-database)[event4u/data-helpers

Framework-agnostic PHP library for data mapping, DTOs and utilities. Includes DataMapper, SimpleDto/LiteDto, DataAccessor/Mutator/Filter and helper classes (MathHelper, EnvHelper, etc.). Works with Laravel, Symfony/Doctrine or standalone PHP.

1421.5k](/packages/event4u-data-helpers)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
