Md Adil Md Adil - 4 months ago 12
PHP Question

Extending Eloquent model with different model

<?php

class Page extends Eloquent {

}

class Article extends Page {
function __construct($attributes = []) {
parent::__construct($attributes);
$this->where('type', 'article');
}
}

$articles = Article::all();
// SELECT * FROM pages WHERE type = 'article'


The page table has many types of data, I want to separate these data by model class, I tried the above query but
where()
function isn't even being called in
__constructor()

Answer
<?php

class Page extends Eloquent {

}

class Article extends Page {
    function __construct($attributes = []) {
       if($attributes) {
          $attributes['type'] = 'article';
       }
        parent::__construct($attributes);

    }
    public function newQuery() {
        return parent::newQuery()->where('type', 'article');
   }    

}

$articles = Article::all();
// SELECT * FROM pages WHERE type = 'article'