2

Is it possible to create a custom query builder inside a model and return the query? Not a stressing issue but would be helpful.

/* Controller */

public function getOrders() 
{
   $orders = \App\Order::where('is_new', 1)->getFromUserStore();
}

/* Order Model */

public function getFromUserStore() 
{
  if(\Auth::user()->store->id == 1)
  {
      return $this->get();
  }
  else
  {
      return $this->where('status_id', 1)->get();
  }
}

Thanks

3
  • It's part of your question per se but I suggest you use the use operator for your namespace to avoid using the backslash all the time. For your controller, your should use App\Order; and for your model use Illuminate\Support\Facades\Auth; Commented May 4, 2016 at 19:35
  • @Wistar, I typically use use.. is there a performance issue with using the backslash? Thanks for the input. Commented May 4, 2016 at 20:09
  • I dont know about performance issue. Also, is the answer working? Commented May 4, 2016 at 20:21

1 Answer 1

4

I believe you are looking for Query Scope

Scopes allow you to define common sets of constraints that you may easily re-use throughout your application.

/* Controller */  
public function getOrders() 
{
   $orders = \App\Order::where('is_new', 1)->getFromUserStore()->get();
}


/* Order Model */
public function scopeGetFromUserStore($query) 
{
  if(\Auth::user()->store->id == 1)
  {
      return $query;
  }
  else
  {
      return $query->where('status_id', 1);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I'm looking for. Thank you.

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.