0
votes

I followed this tutorial and created a user model. I would like to create a superclass so that every model has the same timestamp value and a scope method. Is creating a superclass the correct method to do this? How do I extend a custom Eloquent model in Codeigniter?

I have the following idea, but i'm stuck on the custom model extends part.

CustomModel.php:

use \Illuminate\Database\Eloquent\Model as Eloquent;

class CustomModel extends Eloquent {
    protected function getDateFormat() {
        return 'U';
    }
    protected function scopeUser($query,$userID) {
        return $query->where('user_id','=',$userID);
    }
}

User.php:

class User extends CustomModel {

}

I thought about adding a manual include inside the User.php file, but I don't think it is a nice solution. I also prefer not to autoload the CustomModel class.

1
Did you think about using a trait for it? - Pawel Bieszczad
So you think I should make a trait with the dateformat and scope and then add a use line to all my models? - Meneer Venus
Either that or extend the eloquent model and make all you models extend the new model. Don't forget to composer du and using the right namespaces. - Pawel Bieszczad

1 Answers

1
votes

You can create core model with extending working model from that one. Create MY_Model in core directory with specific functionality you want to use in other models:

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

use \Illuminate\Database\Eloquent\Model as Eloquent;

class MY_Model extends Eloquent {
    protected function getDateFormat() {
        return 'U';
    }
    protected function scopeUser($query,$userID) {
        return $query->where('user_id','=',$userID)
    }
}

Than extend any model from models directory from MY_Model.