dimanche 21 août 2016

Integrity constraint violation: 1062 Duplicate entry

I am receiving 2 errore while submitting a signup form using an email that already been inserted be

Integrity constraint violation: 1062 Duplicate entry 'test@test.com' for key 'users_email_unique'

.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test@test.com' for key 'users_email_unique'

I have database index users_email_unique which causes the error but how can i handle such error

Model

 <?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {
    protected $table = "users";
protected $fillable = array('first_name', 'last_name', 'password', 'email');
protected $hidden = ['password', 'remember_token'];

public function roles() {
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}

public function hasAnyRole($roles) {
    if(is_array($roles)) {
        foreach($roles as $role) {
            if($this->hasRole($role)) {
                return true;
            }
        }
    }
    else {
        if($this->hasRole($roles)) {
            return true;
        }
    }

    return false;
}

public function hasRole($role) {
    if($this->roles()->where('name', $role)->first()) {
        return true;
    }

    return false;
    }
}

Controller

    <?php

namespace App\Http\Controllers;
use App\Post;
use App\ContactMessage;
use App\User;
use App\Role;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller {
    public function postSignUp(Request $request) {
    $rules = [
        'first_name' => 'required|min:3|max:80|alpha',
        'last_name' => 'required|min:3|max:80|alpha',
        'email' => 'required|between:3,64|email',
        'password' => 'required|alphaNum|between:4,8|confirmed',
        'password_confirmation'=> 'required|alphaNum|between:4,8'
    ];

    $validator = Validator::make(Input::all(), $rules);

    if($validator->fails()){
        return Redirect::route('signup')->withErrors($validator)->withInput();
    }

    $user               = new User();
    $user->first_name   = $request['first_name'];
    $user->last_name    = $request['last_name'];
    $user->email        = $request['email'];
    $user->password     = bcrypt($request['password']);

    if($user->save()){dd('aaaaa');
        $user->roles()->attach(Role::where('name', 'User')->first());

        Auth::login($user);

        return redirect()->route('blog.index');
   }
   else {
       dd('sssss');
   }
    }
}

Routes

Route::get('/signup', ['uses' => 'AdminController@getSignUp','as' => 'signup']);
Route::post('/signup', ['uses' => 'AdminController@postSignUp','as' => 'signup']);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire