1

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();
2
  • How are you calling it in your code? Commented Aug 4, 2016 at 8:31
  • I edited my post with the answer to your question Commented Aug 4, 2016 at 8:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thats a good approach but I think its not the best one on this scenario since I have other methods that need this $baseQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.