PHP code example of craftix / lite-eloquent

1. Go to this page and download the library: Download craftix/lite-eloquent library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

craftix / lite-eloquent example snippets




use Craftix\Eloquent\DB;
use PDO;

// Create a PDO connection
$pdo = new PDO(
    'mysql:host=localhost;dbname=db_name',
    'username',
    'password',
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

// Initialize DB instance
$db = new DB($pdo);

// Start querying!
$users = $db->table('users')->get();



use Craftix\Eloquent\DatabaseManager;
use PDO;

// Initialize singleton
DatabaseManager::init(
    new PDO('mysql:host=localhost;dbname=db_name', 'username', 'password')
);

// Use static methods
$users = DatabaseManager::table('users')->get();

// Get all users
$users = $db->table('users')->get();

// Select specific columns
$users = $db->table('users')
    ->select('id', 'name', 'email')
    ->get();

// Get first record
$user = $db->table('users')->first();

// Get single column as array
$emails = $db->table('users')->pluck('email');

// Simple where
$users = $db->table('users')
    ->where('status', '=', 'active')
    ->get();

// Where with default operator (=)
$users = $db->table('users')
    ->where('age', 25)
    ->get();

// Multiple conditions (AND)
$users = $db->table('users')
    ->where('status', 'active')
    ->where('age', '>', 18)
    ->get();

// OR conditions
$users = $db->table('users')
    ->where('status', 'active')
    ->orWhere('status', 'pending')
    ->get();

// WHERE IN
$users = $db->table('users')
    ->whereIn('id', [1, 2, 3, 4, 5])
    ->get();

// WHERE NOT IN
$users = $db->table('users')
    ->whereNotIn('status', ['banned', 'deleted'])
    ->get();

// WHERE BETWEEN
$users = $db->table('users')
    ->whereBetween('age', 18, 65)
    ->get();

// WHERE NULL / NOT NULL
$users = $db->table('users')
    ->whereNull('deleted_at')
    ->get();

$users = $db->table('users')
    ->whereNotNull('email_verified_at')
    ->get();

// WHERE LIKE
$users = $db->table('users')
    ->whereLike('name', '%john%')
    ->get();

// WHERE NOT LIKE
$users = $db->table('users')
    ->whereNotLike('email', '%@spam.com')
    ->get();

// Nested WHERE groups
$users = $db->table('users')
    ->where('status', 'active')
    ->where(function($query) {
        $query->where('age', '>', 18)
              ->orWhere('verified', true);
    })
    ->get();

// INNER JOIN
$users = $db->table('users')
    ->join('profiles', 'users.id', '=', 'profiles.user_id')
    ->select('users.*', 'profiles.bio')
    ->get();

// LEFT JOIN
$users = $db->table('users')
    ->leftJoin('profiles', 'users.id', '=', 'profiles.user_id')
    ->get();

// RIGHT JOIN
$users = $db->table('users')
    ->rightJoin('profiles', 'users.id', '=', 'profiles.user_id')
    ->get();

// Complex JOIN with conditions
$users = $db->table('users')
    ->join('orders', function($join) {
        $join->on('users.id', '=', 'orders.user_id')
             ->where('orders.status', '=', 'completed');
    })
    ->get();

// Multiple JOINs
$orders = $db->table('orders')
    ->join('users', 'orders.user_id', '=', 'users.id')
    ->join('products', 'orders.product_id', '=', 'products.id')
    ->select('orders.*', 'users.name', 'products.title')
    ->get();

// ORDER BY
$users = $db->table('users')
    ->orderBy('created_at', 'DESC')
    ->get();

// Multiple ORDER BY
$users = $db->table('users')
    ->orderBy('status', 'ASC')
    ->orderBy('name', 'ASC')
    ->get();

// ORDER BY DESC (shortcut)
$users = $db->table('users')
    ->orderByDesc('created_at')
    ->get();

// Random order
$users = $db->table('users')
    ->inRandomOrder()
    ->get();

// LIMIT
$users = $db->table('users')
    ->limit(10)
    ->get();

// OFFSET
$users = $db->table('users')
    ->offset(20)
    ->limit(10)
    ->get();

// DISTINCT
$emails = $db->table('users')
    ->distinct()
    ->select('email')
    ->get();

// Length-aware pagination (with total count)
$paginator = $db->table('users')
    ->paginate($page = 1, $perPage = 15);

// Access pagination data
$users = $paginator->items(); // Array of users
$total = $paginator->total(); // Total count
$currentPage = $paginator->currentPage();
$perPage = $paginator->perPage();
$totalPages = $paginator->totalPages();
$hasMore = $paginator->hasMorePages();

// Pagination info
$info = $paginator->getPaginationInfo();
// Returns: ['total', 'perPage', 'from', 'to', 'pages', 'currentPage', 'previousPage', 'nextPage']

// Simple pagination (no total count, faster)
$paginator = $db->table('users')
    ->simplePaginate($page = 1, $perPage = 15);

$hasMore = $paginator->hasMorePages();

// Single insert
$affected = $db->table('users')
    ->insert([
        'name' => 'John Doe',
        'email' => '[email protected]',
        'age' => 30
    ]);

// Bulk insert
$affected = $db->table('users')
    ->insert([
        ['name' => 'John', 'email' => '[email protected]'],
        ['name' => 'Jane', 'email' => '[email protected]'],
        ['name' => 'Bob', 'email' => '[email protected]']
    ]);

// Insert and get ID
$id = $db->table('users')
    ->insertGetId([
        'name' => 'John Doe',
        'email' => '[email protected]'
    ], 'id'); // Second parameter is the ID column name (default: 'id')

// Insert or ignore (Pgsql: ON CONFLICT DO NOTHING, MySQL: INSERT IGNORE)
$affected = $db->table('users')
    ->insertOrIgnore([
        'email' => '[email protected]',
        'name' => 'John Doe'
    ], ['email']); // Unique columns for conflict detection

// MySQL: ON DUPLICATE KEY UPDATE
// Pgsql: ON CONFLICT DO UPDATE

// Upsert with auto-update of all non-unique columns
$affected = $db->table('users')
    ->upsert(
        ['email' => '[email protected]', 'name' => 'John Doe', 'age' => 30],
        ['email'], // Unique columns
        null // Update all non-unique columns
    );

// Upsert with specific columns to update
$affected = $db->table('users')
    ->upsert(
        ['email' => '[email protected]', 'name' => 'John Doe', 'age' => 30],
        ['email'], // Unique columns
        ['name', 'age'] // Columns to update on conflict
    );

// Bulk upsert
$affected = $db->table('users')
    ->upsert(
        [
            ['email' => '[email protected]', 'name' => 'John'],
            ['email' => '[email protected]', 'name' => 'Jane']
        ],
        ['email'],
        ['name']
    );

// Update with WHERE clause
$affected = $db->table('users')
    ->where('id', 1)
    ->update([
        'name' => 'John Updated',
        'email' => '[email protected]'
    ]);

// Update multiple rows
$affected = $db->table('users')
    ->where('status', 'pending')
    ->update(['status' => 'active']);

// Update with JOIN
$affected = $db->table('users')
    ->join('profiles', 'users.id', '=', 'profiles.user_id')
    ->where('profiles.verified', true)
    ->update(['users.status' => 'verified']);

// Get generated SQL (for debugging)
$sql = null;
$affected = $db->table('users')
    ->where('id', 1)
    ->update(['name' => 'John'], $sql);
echo $sql; // Outputs the generated SQL

// Delete with WHERE clause
$affected = $db->table('users')
    ->where('status', 'deleted')
    ->delete();

// Delete with multiple conditions
$affected = $db->table('users')
    ->where('status', 'inactive')
    ->where('last_login', '<', '2024-01-01')
    ->delete();

// Delete with JOIN
$affected = $db->table('users')
    ->join('profiles', 'users.id', '=', 'profiles.user_id')
    ->where('profiles.banned', true)
    ->delete();

// Get generated SQL
$sql = null;
$affected = $db->table('users')
    ->where('id', 1)
    ->delete($sql);

use Craftix\Eloquent\Grammar\Expression;

// Using raw expressions in queries
$users = $db->table('users')
    ->select($db->raw('COUNT(*) as total'))
    ->get();

// Raw expressions in WHERE
$users = $db->table('users')
    ->where($db->raw('DATE(created_at)'), '=', '2024-01-01')
    ->get();

// Raw expressions in JOIN
$users = $db->table('users')
    ->join('profiles', $db->raw('users.id'), '=', $db->raw('profiles.user_id'))
    ->get();

// Or use Expression::make()
$expr = Expression::make('NOW()');
$users = $db->table('users')
    ->where('created_at', '>', $expr)
    ->get();

// Using DB instance
$db->beginTransaction();
try {
    $db->table('users')->insert(['name' => 'John']);
    $db->table('profiles')->insert(['user_id' => 1, 'bio' => 'Bio']);
    $db->commit();
} catch (Exception $e) {
    $db->rollBack();
    throw $e;
}

// Using transaction closure
$db->transaction(function() use ($db) {
    $db->table('users')->insert(['name' => 'John']);
    $db->table('profiles')->insert(['user_id' => 1, 'bio' => 'Bio']);
});

// Check if in transaction
if ($db->inTransaction()) {
    // Currently in a transaction
}

// Using singleton
DatabaseManager::beginTransaction();
try {
    DatabaseManager::table('users')->insert(['name' => 'John']);
    DatabaseManager::commit();
} catch (Exception $e) {
    DatabaseManager::rollBack();
}

// Or with closure
DatabaseManager::transaction(function() {
    DatabaseManager::table('users')->insert(['name' => 'John']);
});

$users = $db->table('users')->get();

// Collection methods
$users->count(); // Get count
$users->isEmpty(); // Check if empty
$users->first(); // Get first item
$users->last(); // Get last item
$users->pluck('email'); // Get array of email values
$users->plucked('email'); // Get new collection with emails

// Filtering and mapping
$users->filter(fn($user) => $user['age'] > 18);
$users->map(fn($user) => strtoupper($user['name']));

// Searching
$user = $users->find(fn($user) => $user['id'] === 1);
$exists = $users->contains(['id' => 1]);

// Array access
$firstUser = $users[0];
$users[] = ['id' => 100, 'name' => 'New User'];

// Convert to array/JSON
$array = $users->toArray();
$json = $users->toJson();

// Convert results to custom objects
$users = $db->table('users')
    ->objectConverter(function($row) {
        return new User($row);
    })
    ->get();

// Now $users contains User objects instead of arrays
foreach ($users as $user) {
    echo $user->getName();
}

// Get the SQL query without executing
$sql = $db->table('users')
    ->where('status', 'active')
    ->toSql();

echo $sql; // SELECT * FROM `users` WHERE `status` = :v1;

use Craftix\Eloquent\Grammar\Dialects\MySqlDialect;
use Craftix\Eloquent\Grammar\Dialects\PostgresDialect;

// Set MySQL dialect
$db->setDialect(new MySqlDialect());

// Set Pgsql dialect
$db->setDialect(new PostgresDialect());

// ✅ Safe - Uses parameter binding
$users = $db->table('users')
    ->where('email', $userEmail)
    ->get();

// ⚠️ Only use raw expressions when absolutely necessary
$users = $db->table('users')
    ->where($db->raw('email'), '=', $userEmail) // Still safe due to binding
    ->get();

use Craftix\Eloquent\Data\QueryBuilderException;

try {
    $users = $db->table('users')->get();
} catch (QueryBuilderException $e) {
    $errorCode = $e->getCode();
    $message = $e->getMessage();
    
    // Error codes:
    // 0 - Database execution error
    // 1000 - Invalid order type
    // 1001 - Invalid join type
    // 2000 - Missing table
    // 2001 - Missing columns
    // 2002 - Dangerous query (UPDATE/DELETE without WHERE)
    // 2004 - Invalid query
}