简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM