PHP code example of onlyphp / codeigniter3-model

1. Go to this page and download the library: Download onlyphp/codeigniter3-model 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/ */

    

onlyphp / codeigniter3-model example snippets




if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class User_model extends MY_Model
{
    // Database Configuration
    public $connection = 'default';       // Database connection group from config (OPTIONAL)
    public $table = 'users';              // Table name (REQUIRED)
    public $primaryKey = 'id';            // Primary key column (REQUIRED)
    
    // Fillable & Protected Fields
    public $fillable = [                  // Fields that can be mass assigned (REQUIRED)
        'name',
        'email',
        'password',
        'status'
    ];

    public $protected = ['id'];           // Fields that cannot be mass assigned (OPTIONAL)
    
    // Timestamp Configuration
    public $timestamps = TRUE;            // Enable/disable timestamps (OPTIONAL)
    public $timestamps_format = 'Y-m-d H:i:s'; // Define format, Default is Y-m-d H:i:s (OPTIONAL)
    public $timezone = 'Asia/Kuala_Lumpur'; // Define timezone, Default is Asia/Kuala_Lumpur (OPTIONAL)
    public $created_at = 'created_at';    // Created at column name (OPTIONAL)
    public $updated_at = 'updated_at';    // Updated at column name (OPTIONAL)
    public $deleted_at = 'deleted_at';    // Deleted at column name (OPTIONAL)
    
    // Soft Delete Configuration
    public $softDelete = true;            // Enable/disable soft deletes, Default is false (OPTIONAL)
    
    // Query Result Modifications
    public $appends = ['full_name'];      // Append custom attributes (OPTIONAL)
    public $hidden = ['password'];        // Hide specific columns (OPTIONAL)
    
    // Validation Rules
    public $_validationRules = [          // General validation rules
        'email' => '

// Basic query with where clause
$users = $this->user_model
    ->where('status', 'active')
    ->orderBy('created_at', 'desc')
    ->get();

// Complex where conditions
$posts = $this->post_model
    ->whereNotNull('published_at')
    ->whereBetween('created_at', ['2024-01-01', '2024-12-31'])
    ->get();

// Enable soft deletes in your model
protected $softDelete = true;
protected $deleted_at = 'deleted_at'; // (OPTIONAL) Default is deleted_at

// Soft delete a record
$this->user_model->destroy($id);

// Include soft deleted records in query
$allUsers = $this->user_model
    ->withTrashed()
    ->get();

// Restore soft deleted record
$this->user_model->restore($id);

// User Model with relationships
class User_model extends MY_Model
{
    public $table = 'users';
    public $primaryKey = 'id';

    public function posts()
    {
        return $this->hasMany('Post_model', 'user_id', 'id');
    }

    public function profile()
    {
        return $this->hasOne('Profile_model', 'user_id', 'id');
    }
}

// Using relationships with eager loading
$users = $this->user_model
    ->with(['posts' => function($query) {
        $query->select('id, title, content')
            ->where('status', 'published');
    }])
    ->with('profile')
    ->get();

// Controller method for basic pagination
public function listUsers()
{
    $search = $this->input->get('search');
    $page = $this->input->get('page', 1);
    
    $users = $this->user_model
        ->where('status', 'active')
        ->paginate(10, $page, $search);
        
    $this->load->view('users/list', ['users' => $users]);
}

// Controller method for DataTables
public function getUsersData()
{
    $paginateData = $this->user_model
        ->setPaginateFilterColumn([
            null,           // Row number column
            'name',         // Searchable columns
            'email',
            'status'
        ])
        ->with('profile')  // Eager load relationships
        ->paginate_ajax($_POST);
        
    // Format the response
    if (!empty($paginateData['data'])) {
        foreach ($paginateData['data'] as $key => $user) {
            $paginateData['data'][$key] = [
                ($key + 1),
                $user['name'],
                $user['email'],
                $user['profile']['phone'],
                $this->_generateActions($user['id'])
            ];
        }
    }
    
    echo json_encode($paginateData);
}

private function _generateActions($id)
{
    return '
        <button onclick="editUser('.$id.')" class="btn btn-sm btn-primary">Edit</button>
        <button onclick="deleteUser('.$id.')" class="btn btn-sm btn-danger">Delete</button>
    ';
}

// Enable XSS protection for all output
$users = $this->user_model
    ->safeOutput()
    ->get();

// Exclude specific fields from XSS protection
$posts = $this->post_model
    ->safeOutputWithException(['content', 'html_description'])
    ->get();

// Model with validation rules
class User_model extends MY_Model
{
    public $_validationRules = [
        'email' => '[6]'
    ];
}

// Controller
class UserController extends CI_Controller
{
    public function singleData()
    {
        // Create with validation
        $userData = [
            'name' => 'John Doe',
            'email' => '[email protected]'
        ];

        // Create record with validation
        $response = $this->user_model->create($userData);
    }

    public function multipleData()
    {
        // Batch create multiple records
        $usersData = [
            ['name' => 'John', 'email' => '[email protected]'],
            ['name' => 'Jane', 'email' => '[email protected]']
        ];

        $this->user_model->batchCreate($usersData);
    }
}

// Complex query with multiple conditions
$activeUsers = $this->user_model
    ->select('users.*, COUNT(posts.id) as post_count')
    ->leftJoin('posts', 'posts.user_id = users.id')
    ->where('users.status', 'active')
    ->whereYear('users.created_at', '>=', date('Y'))
    ->whereExists(function($query) {
        $query->select(1)
            ->from('user_logins')
            ->whereRaw('user_logins.user_id = users.id');
    })
    ->groupBy('users.id')
    ->having('post_count >', 5)
    ->orderBy('post_count', 'DESC')
    ->with(['profile', 'settings'])
    ->get();

// Batch operations
$this->user_model->batchCreate([
    ['name' => 'John', 'email' => '[email protected]'],
    ['name' => 'Jane', 'email' => '[email protected]']
]);

// Transaction example
$this->db->trans_begin();
try {
    $userId = $this->user_model->create($userData);
    $this->profile_model->create(['user_id' => $userId, ...]);
    $this->db->trans_commit();
} catch (Exception $e) {
    $this->db->trans_rollback();
    throw $e;
}

// Complex query with multiple conditions
$users = $this->user_model
    ->select('users.*, roles.name as role_name')
    ->where('status', 'active')
    ->whereYear('created_at', '2024')
    ->whereNotNull('email_verified_at')
    ->leftJoin('roles', 'roles.id = users.role_id')
    ->orderBy('created_at', 'DESC')
    ->get();

// Chunk processing for large datasets
$this->user_model->chunk(100, function($users) {
    foreach ($users as $user) {
        // Process each user
    }
});

// ---------------
// PLUCK EXAMPLES
// ---------------

// Example 1: Get all usernames as a simple array
$usernames = $this->user_model->pluck('username');
// Result: ['john_doe', 'jane_smith', 'bob_jones', ...]

// Example 2: Get usernames keyed by user ID
$usernamesById = $this->user_model->pluck('username', 'id');
// Result: [1 => 'john_doe', 2 => 'jane_smith', 3 => 'bob_jones', ...]

// Example 3: Get values from related models using dot notation
$this->user_model->with('profile');
$userCities = $this->user_model->pluck('profile.city');
// Result: ['New York', 'Los Angeles', 'Chicago', ...]

// Example 4: Get values from related models with custom keys
$this->user_model->with(['profile', 'role']);
$userCitiesByRole = $this->user_model->pluck('profile.city', 'role.name');
// Result: ['admin' => 'New York', 'editor' => 'Los Angeles', ...]

// ---------------
// LAZY EXAMPLES
// ---------------

// Setup for examples
$users = $this->User_model
    ->where('status', 'active')
    ->lazy(200);

// Example 1: count() - Get the total number of items in the collection
$totalUsers = $users->count();
echo "Total active users: " . $totalUsers;
// Note: count() iterates through the entire collection the first time
// it's called, then caches the result for subsequent calls

// Example 2: first() - Get the first item from the collection
// Without callback
$firstUser = $users->first();
echo "First user ID: " . $firstUser['id'];

// With callback to find specific item
$adminUser = $users->first(function($user) {
    return $user['role'] === 'admin';
}, null);
echo "First admin user: " . ($adminUser ? $adminUser['username'] : 'No admin found');

// Example 3: pluck() - Extract a specific key from all items
$usernames = $users->pluck('username');
foreach ($usernames as $username) {
    echo "Username: " . $username . "<br>";
}

// Example 4: chunk() - Split the collection into smaller collections
$userChunks = $users->chunk(5);
foreach ($userChunks as $index => $chunk) {
    echo "Processing chunk #" . ($index + 1) . "<br>";
    foreach ($chunk as $user) {
        echo "- Processing user: " . $user['username'] . "<br>";
    }
}

// Example 5: map() - Transform each item in the collection
$transformedUsers = $users->map(function($user) {
    $user['full_name'] = $user['first_name'] . ' ' . $user['last_name'];
    $user['is_adult'] = $user['age'] >= 18;
    return $user;
});

foreach ($transformedUsers as $user) {
    echo $user['full_name'] . " is " . ($user['is_adult'] ? 'an adult' : 'a minor') . "<br>";
}

// Example 6: filter() - Keep only items that pass the truth test
$adultUsers = $users->filter(function($user) {
    return $user['age'] >= 18;
});

foreach ($adultUsers as $user) {
    echo "Adult user: " . $user['username'] . " (age: " . $user['age'] . ")<br>";
}

// Example 7: reject() - Remove items that pass the truth test
$nonAdminUsers = $users->reject(function($user) {
    return $user['role'] === 'admin';
});

foreach ($nonAdminUsers as $user) {
    echo "Non-admin user: " . $user['username'] . "<br>";
}

// Example 8: each() - Execute code for each item
$users->each(function($user) {
    echo "Processing user " . $user['id'] . ": " . $user['username'] . "<br>";
    // Perform operations on the user
    return true; // continue iteration (return false to break)
});

// Example 9: tap() - Perform an operation on the collection and return it
$users->tap(function($collection) {
    echo "The collection has " . $collection->count() . " items.<br>";
})->each(function($user) {
    // Process each user
});

// Example 10: all() - Get all items as an array
$allUsers = $users->all();
print_r($allUsers); // Full array of all users

// Example 11: implode() - Concatenate values of a given key as a string
$allUsernames = $users->implode('username', ', ');
echo "All usernames: " . $allUsernames;

// Example 12: take() - Get a specific number of items
$firstTenUsers = $users->take(10);
foreach ($firstTenUsers as $user) {
    echo "User from first 10: " . $user['username'] . "<br>";
}

// Example 13: skip() - Skip a specific number of items
$afterFirstHundred = $users->skip(100)->take(10);
foreach ($afterFirstHundred as $user) {
    echo "User after first 100: " . $user['username'] . "<br>";
}

// Example 14: Chaining multiple methods
$result = $this->User_model
    ->where('status', 'active')
    ->lazy(150)
    ->filter(function($user) {
        return $user['age'] >= 21;
    })
    ->map(function($user) {
        $user['full_name'] = $user['first_name'] . ' ' . $user['last_name'];
        return $user;
    })
    ->skip(10)
    ->take(5)
    ->pluck('full_name')
    ->all();

print_r($result); // Array of 5 full names, after skipping the first 10

// Example 15: Using setChunkSize to change chunk size after creation
$users = $this->User_model->lazy(); // Default chunk size
$users->setChunkSize(50); // Change to smaller chunks for memory optimization

// Example 16: Using lazy collection with complex queries
$specialUsers = $this->User_model
    ->with(['profile', 'orders'])
    ->where('status', 'active')
    ->where('created_at >', date('Y-m-d', strtotime('-30 days')))
    ->orderBy('created_at', 'DESC')
    ->lazy(75)
    ->filter(function($user) {
        // Only users with complete profiles
        return !empty($user['profile']) && 
               !empty($user['profile']['address']) && 
               !empty($user['profile']['phone']);
    });

// Example 17: Memory-efficient large data export
$fileName = 'users_export_' . date('Y-m-d') . '.csv';
$file = fopen($fileName, 'w');
fputcsv($file, ['ID', 'Username', 'Email', 'Full Name', 'Created Date']);

$this->User_model
    ->lazy(200)
    ->each(function($user) use ($file) {
        fputcsv($file, [
            $user['id'],
            $user['username'],
            $user['email'],
            $user['first_name'] . ' ' . $user['last_name'],
            $user['created_at']
        ]);
    });

fclose($file);
echo "Export completed to $fileName";

// Example 18: Data aggregation without loading everything into memory
$stats = [
    'total' => 0,
    'age_sum' => 0,
    'min_age' => PHP_INT_MAX,
    'max_age' => 0,
    'by_country' => []
];

$this->User_model
    ->lazy(300)
    ->each(function($user) use (&$stats) {
        $stats['total']++;
        $stats['age_sum'] += $user['age'];
        $stats['min_age'] = min($stats['min_age'], $user['age']);
        $stats['max_age'] = max($stats['max_age'], $user['age']);
        
        $country = $user['country'];
        if (!isset($stats['by_country'][$country])) {
            $stats['by_country'][$country] = 0;
        }
        $stats['by_country'][$country]++;
    });

$stats['avg_age'] = $stats['age_sum'] / $stats['total'];
print_r($stats);

// ---------------
// FILTER EXAMPLES
// ---------------

// Example 1: Filter active premium users
$premiumUsers = $this->user_model->filter(function($user) {
    return $user['subscription_type'] === 'premium' && $user['is_active'] === 1;
});

// ---------------
// SORT BY EXAMPLES
// ---------------

// Example 1: Get all users with their relationships and sort by name
$users = $this->User_model->with('profile', 'profile.roles', 'department')
    ->setAppends(['status_badge'])
    ->safeOutputWithException(['status_badge'])
    ->withTrashed()
    ->sortBy('name');

// Example 2: Sort by role rank (from the first profile record)
$sortedByRoleRank = $this->User_model->sortBy('profile.0.roles.role_rank', SORT_DESC);

// Example 3: Sort by department name (handles null values)
$sortedByDept = $this->User_model->sortBy(function($user) {
    return $user['department'] ? $user['department']['department_name'] : null;
});

// Example 4: Sort by multiple criteria - first by department name, then by name
$sortedMultiple = $this->User_model->sortByMultiple([
    ['department.department_name', 'asc'],
    ['name', 'asc']
]);

// Example 5: Sort by main profile role rank
$sortedByMainRole = $this->User_model->sortBy(function($user) {
    if (empty($user['profile'])) return null;
    
    // Find the main profile
    foreach ($user['profile'] as $profile) {
        if ($profile['is_main'] == '1') {
            return $profile['roles']['role_rank'];
        }
    }
    
    return null;
});

// ---------------
// EXISTS / DOES NOT EXISTS EXAMPLES
// ---------------

// Example 1: Check if there are any pending orders
if ($this->order_model->where('status', 'pending')->doesntExist()) {
    // Logic process
}

// Example 2: Show empty state for products
if ($this->product_model->where('category_id', 5)->exists()) {
    // Logic process
}

// Example 3: Set the value to the variable
$hasAdmin = $this->User_model->where('is_role', 'superadmin')->exists();

// ---------------
// CONTAINS EXAMPLES
// ---------------

// Example 1: Check if any premium users exist
$hasPremiumUsers = $this->user_model->contains('subscription_type', 'premium');

// Example 2: Check with callback
$hasNewOrders = $this->order_model->contains(function($order) {
    return strtotime($order['created_at']) > strtotime('-24 hours');
});

$hasITDepartment = $this->User_model->contains(function($user) {
    return isset($user['department']) && $user['department']['department_code'] === 'IT';
});

// Example 3: Check if any superadmin users exist
$hasSuperAdmin = $this->User_model->contains('name', 'SUPER ADMINISTRATOR');

// Example 4: Check if first roles is rank up to 5000
$hasHighRankRole = $this->User_model->contains('profile.0.roles.role_rank', '>', '5000');

bash
"scripts": {
    "post-install-cmd": [
        "@php vendor/onlyphp/codeigniter3-model/scripts/install.php"
    ],
    "post-update-cmd": [
        "@php vendor/onlyphp/codeigniter3-model/scripts/update.php"
    ]
}