Home > Software design >  How to add if statment in select query in Laravel
How to add if statment in select query in Laravel

Time:12-21

I want to write select query from below condition

$query = \App\Models\User::where('id', $user->id)

if this user is_email_verify == 1 means select

$query = \App\Models\User::where('id', $user->id)->slect('is_email_verify')->first(); 

if this user is_phone_verify == 1 means select

$query = \App\Models\User::where('id', $user->id)->slect('is_email_verify', 'is_email_verify')->first();

Select column name base on that value

if this user have is_email_verify then select is_email_verify. if this user have is_phone_verify then select is_phone_verify. if this user have both verify then select is_phone_verify and is_email_verify.

CodePudding user response:

to select the is_email_verify column if the user has an email that is verified and the is_phone_verify column if the user has a phone that is verified, you can use a query like this:

$query = \App\Models\User::where('id', $user->id)
    ->select(function($query) {
        if ($user->is_email_verify == 1) {
            $query->addSelect('is_email_verify');
        }
        if ($user->is_phone_verify == 1) {
            $query->addSelect('is_phone_verify');
        }
    })
    ->first();

This query will select the is_email_verify and is_phone_verify columns if the corresponding fields are set to 1, and will only select the id column if neither of these fields is set to 1.

CodePudding user response:

You can also pass a ternary condition into addSelect method.

return \App\Models\User::where('id', $user->id)
    ->addSelect($user->is_email_verify === 1
         ? 'is_email_verify'
         : 'is_phone_verify'
    )->first();

Regards.

  • Related