Emmanuel-Ab
Emmanuel-Ab

Reputation: 331

How to use if statement in where condition in Laravel?

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?

Upvotes: 0

Views: 63

Answers (1)

Emmanuel-Ab
Emmanuel-Ab

Reputation: 331

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

Upvotes: 1

Related Questions