Codeigniter 4 – Creating Models with Examples

Creating a Basic Model

- Create a new file in the app/Models directory.
- Extend the CodeIgniter\Model class.
- Define the table name and primary key.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
}

Creating a Model with Validation

- Use the validate() method to define validation rules.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';

    protected $validationRules = [
        'name' => 'required',
        'email' => 'required|valid_email',
    ];
}

Creating a Model with Relationships

- Use the belongsTo(), hasMany(), and hasOne() methods to define relationships.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';

    public function posts()
    {
        return $this->hasMany('App\Models\Post', 'user_id');
    }
}

Creating a Model with Custom Methods

- Define custom methods to perform specific tasks.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';

    public function getUserPosts($id)
    {
        return $this->where('id', $id)->first()->posts;
    }
}

Creating a Model with Hooks

- Use the beforeInsert(), afterInsert(), beforeUpdate(), and afterUpdate() methods to define hooks.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';

    public function beforeInsert(array $data)
    {
        // Perform some logic before inserting
    }
}

I hope this helps! Let me know if you have any further questions or need more information.

Note: Creating models in CodeIgniter 4 provides a simple and intuitive way to interact with the database. It helps to keep the code organized and maintainable.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0