Md Adil
Md Adil

Reputation: 307

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()

Upvotes: 1

Views: 1197

Answers (2)

Md Adil
Md Adil

Reputation: 307

<?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'

Upvotes: 0

nextt1
nextt1

Reputation: 3988

You simply want implement scope in Model. So check Query Scope but It must be defined in the model class. If you want a seperate class that uses that scope as the basis for querying check out global scope. https://softonsofa.com/laravel-how-to-define-and-use-eloquent-global-scopes/

Upvotes: 1

Related Questions