konz laugoko
konz laugoko

Reputation: 79

how to create new user only if there is data in database-Laravel

I have done programming with other frameworks but this is new to me, thanks for your time in advanced, I'm trying to create new user on a condition that if there is data in another table then new user is created otherwise not I have put my code inside if else statement and is throwing errors.

my function for creating new user is listed below:

    protected function create(array $data)
    {
        /*$exists = \DB::table('received_pay')->where('email', $data['email'])->first();  */
          $exists=\DB::table('received_pay')->where('email', '=', $data['email'])->where('token', $data['token'])->exists();


if ($exists === null) {
   // user doesn't exist



        return User::create([
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'token'   => $data['token'],
        ]);

}else{
    return null;
}

}

}

this is the error it throws

Upvotes: 1

Views: 118

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You need to return User instance from the RegisterController@create method by default, you can't return null. So, do this instead of return null;:

return User::where('email', $data['email'])->first();

If it's an option to check if the user exists in the users table, you can use the firstOrCreate method:

protected function create(array $data)
{
    return User::firstOrCreate(['email' => $data['email'], [
        'username' => $data['username'],
        'password' => bcrypt($data['password']),
        'token' => $data['token'],
    ]);
}

Also, you if want to check if a user exists in the received_pay table, you can leave original RegisterController@create method and add this rule to the RegisterController@validator method:

'email' => 'unique:received_pay,email',

This will not allow Laravel to create a new user if a user with the same email already exists in the received_pay table.

Upvotes: 1

Related Questions