0

I want to query the database as follows:

User::where('type', 'student')->where('registered_at', '>=', $year)->get();

if the user type is 'student' I want to get the registered from this year, however if the type is 'faculty' I don't want to have this 'registered_at' condition and want to execute this.

User::where('type', 'faculty')->get();

How to execute this so I have 1 query with kind of an if statement, if type is 'student' than give me only result above this $year and if type is 'faculty' give the results?

3
  • Do you want to get all users which are students with registered_at and all users with type faculty in one list? Commented Apr 8, 2020 at 11:09
  • @UfguFugullu Yes, I found the 'orWhere' clause can have a callback where I can have my conditions. Commented Apr 8, 2020 at 11:17
  • That's great, don't forget to mark the right answer below Commented Apr 8, 2020 at 11:24

1 Answer 1

1

I've found the solution in the documentation.

    User::where(function ($query) {
        $query->where('type', 'student')->where('registered_at', '>=', $year);
    })->orWhere(function($query) {
        $query->where('type', 'faculty');
    })->get();
Sign up to request clarification or add additional context in comments.

Comments

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.