Laravel Adldap2 - Update If Email Exist

257 Views Asked by At

I still have users table, and It has records.

I want to login users If they matched with their AD informations. If their AD informations not exist on my database, then create new record.

But Adldap2 always try to create new record If objectguId field is empty.

my ldap_auth.php file:

    'ldap' => [

        'locate_users_by' => 'userprincipalname',

        'bind_users_by' => 'distinguishedname',

    ],

    'database' => [

        'guid_column' => 'objectguId',

        'username_column' => 'username',

    ],

My LoginController:

        $credentials = $request->only('username', 'password');
        $aw = Auth::attempt($credentials);
        if ($aw) {
            $results = array('status' => 1, "message" => "Login success", "redirect" => "/");
        }

Users logs in with his email and password. And successfully connects.

But It tries to create new record If no matching objectguId. So It returns "Duplicate entry" because this email was created on my database without objectguId.

I want It in case of email matches, so update record. If not, then create new record.

But couldnt solve for any.

1

There are 1 best solutions below

2
AlanCebohin On

Did you try the "updateOrCreate" method?

Spoiler alert: You can try also the "upsert" method. Here is a link well explained with 3 methods. I would use updateOrCreate in you case, but take a look at upsert: https://www.youtube.com/watch?v=J8x268as2qo&ab_channel=LaravelDaily

Note: Here I'm assuming that your 'objectguId' is a column in your 'users' table.

Try to do something like this in your Controller:

$credentials = $request->only('username', 'password');
if(Auth::attempt($credentials)) {
    $aw = Auth::attempt($credentials);
    $user = User::where('username', $request->username)->first();
}

$new_information = [
    'username' => $request->username,
    'password' => $request->password,
    'objectguId' => $user->objectguId,
];
$old_information = [
    'username' => $request->username,
    'password' => $request->password,
];
$user = User::updateOrCreate($old_information, $new_information); // Here, as first parameter you pass what you need to find and, as second parameter, the information you need to update if the query finds the data or create if not

$user->save();