Sebastian M
Sebastian M

Reputation: 491

Class variable in Laravel Model

Lets say I have a "Student" model with functions getActive() and getInactive() like this:

public static function getActive()
{
    return Student::with(['user', 'country', 'course', 'gender', 'language' => function($q){$q->orderBy('name');}])->where('active', 1)->get();
}

public static function getInactive()
{
    return Student::with(['user', 'country', 'course', 'gender', 'language' => function($q){$q->orderBy('name');}])->where('active', 0)->get();
}

As you can see, the only difference is the >where('active', 0) at the end of each query.

I'm trying to declare a global "base query" to which I would append the where condition at the end. Something like this:

$baseQuery;

public function __construct()
{
    $baseQuery = Student::with(['user', 'country', 'course', 'gender', 'language' => function($q){$q->orderBy('name');}]);
}

public static function getActive()
{
    return $baseQuery->where('active', 1)->get();
}

public static function getInactive()
{
    return $baseQuery->where('active', 0)->get();
}

This would not only save me redundant code, it would also make my code more clear and visible but as a newbie I'm struggling with the code.

Any ideas?

EDIT 1:

I'm calling it like this from my controller:

$students = Profile::getActive();

Upvotes: 1

Views: 1364

Answers (2)

SteD
SteD

Reputation: 14027

Use Query Scope

public function scopeRetrieve($query)
{
   return $query->with(['user', 'country', 'course', 'gender', 'language'])->orderBy('name');
}

public static function scopeActive($query)
{
   return $query->where('active', 1);
}

public static function scopeInactive()
{
  return $query->where('active', 0);
}

You can call it like this:

Profile::retrieve()->active()->get();
Profile::retrieve()->inactive()->get();

It encourages reusability since you're breaking them into chunks of its own, next time if you've more constraints or filter you could just add on to it.

Upvotes: 1

tanvirjahan
tanvirjahan

Reputation: 164

You can use whereIn method.The whereIn method verifies that a given column's value is contained within the given array:

public static function getInactiveOrInactive()
{
return Student::with(['user', 'country', 'course', 'gender', 'language' =>   function($q){$q->orderBy('name');}])->->whereIn('active', [0,1])->get();
}

Upvotes: 0

Related Questions