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
    }
});
bash
"scripts": {
    "post-install-cmd": [
        "@php vendor/onlyphp/codeigniter3-model/scripts/install.php"
    ],
    "post-update-cmd": [
        "@php vendor/onlyphp/codeigniter3-model/scripts/update.php"
    ]
}