ddoddsr's avatar

Compare for equality two fields in a record

I want a list of every user that uses their own email in email2, another email field. ( This is a cleanup process. Future entries will not allow the same email to used in both places. ) how to do the where clause?

->where('email, '==', 'email2') won't work.

$staff = DB::table('users')->get();
		foreach($staff as $own) {
				if($own->email == $own->email2) {
    				$this->ownSuperNames[] =  [
        				'user_id' => $own->id, 
        				'user_name' => $own->name,
        				'email' => $own->email, 
        				'email2' => $own->email2,
    				];
				}
        }

As you can see I am doing this the hard way

1 like
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To simplify the process, you can use the whereColumn method in Laravel's query builder to compare two fields in a record. Here's an example of how you can modify the code to achieve this:

$staff = DB::table('users')
    ->whereColumn('email', '=', 'email2')
    ->get();

foreach ($staff as $own) {
    $this->ownSuperNames[] = [
        'user_id' => $own->id,
        'user_name' => $own->name,
        'email' => $own->email,
        'email2' => $own->email2,
    ];
}

The whereColumn method allows you to compare two columns in a table. In this case, it compares the email column with the email2 column. If they are equal, the record is included in the result set.

This approach eliminates the need for the if condition inside the loop, making the code more concise and efficient.

Please or to participate in this conversation.