Julian M. Julian M. - 1 month ago 5x
PHP Question

How to Declare methods in laravel base model

I have several Laravel models which have the same functionallity.

I'm trying to implement some sort of

functionallity but with another logic behind it.

For example: all my models have an "Active" boolean flag, which means that I get all of my languages like:
$language = Language::where('active', 1)->orderBy('name')->get();
. The same goes for hobbies, semesters, etc.

I'm trying to do something like this in my base_model from which all other models extend:

public static function getActive()
return this::where('active', 1)->orderBy('name')->get();

this would save me lots and lots of redundant code, but as a newbie I'm struggling with the code.

How can I dynamically define the Model I want to retrieve?

Any ideas?


You can use Laravel query scopes for this. For example:

//your base model
class BaseModel extends Model
    //every class inheriting from this will have this scope
    public function scopeActive($query)
        return $query->where('active', 1)->orderBy('name')->get();

//your child models will inherit the scope from the parent class
class Language extends BaseModel
    //your model's methods

//use the scope to get all the active languages
$languages = Language::active();