5

i have a problem when i try to create a new user in my database, if I add the users in phpmyadmin i have no problems, but when i try create users in my laravel web, the users has created with this error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '15.236.964-5' for key 'PRIMARY' I dont have idea which is the problem because in the database does not exist the same primary key. The table with problems is:

CREATE TABLE IF NOT EXISTS `users` (
`rut` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` char(60) COLLATE utf8_unicode_ci NOT NULL,
  `edad` int(11) NOT NULL,
  `pais` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `comuna` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `sector` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `tipo` enum('profesor','alumno','administrador_parrilla','administrador_sistema','externo') COLLATE utf8_unicode_ci NOT NULL,
  `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `users`
  ADD PRIMARY KEY (`rut`),
  ADD UNIQUE KEY `usuario_rut_unique` (`rut`),
  ADD UNIQUE KEY `usuario_email_unique` (`email`);

My controller:

class UsuarioController extends Controller
{
 public function index(){
        $users = User::All();
        return view('usuario.index', compact('users'));
    }

    public function create(){
     return view('usuario.create');
    }
    public function store(Request $request) {
         User::create([
             'name' => $request['name'],
             'rut' => $request['rut'],
             'email' => $request['email'],
             'password' => bcrypt($request['password']),             
             'edad' => $request['edad'],
             'pais' => $request['pais'],
             'comuna' => $request['comuna'],
         ]);
        User::create($request->all());
        return redirect('/usuario')->with('message', 'store');
    }

    public function edit($rut){
        $user = User::find($rut);
        return view ('usuario.edit',['user'=>$user]);
    }

    public function update($id, Request $request){
        $user = User::find($id);
        $user -> fill($request->all());
        $user -> save();

        Session::flash('message', 'Usuario Editado Correctamente');
        return Redirect ('/usuario');
    }
}

My Model:

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = "users";
    protected $fillable = [
        'rut', 'name', 'email', 'password', 'edad', 'pais', 'comuna', 'sector', 'tipo',
    ];
/**
    protected $primaryKey = 'rut';

    
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

I can't change the primary key adding auto_increment because i use the "Rut" as a primary key who is the code of identification to people in Chile.

Bullgod
  • 149
  • 1
  • 3
  • 15

3 Answers3

7

Do following steps:

1) Remove ADD UNIQUE KEY usuario_rut_unique (rut).

Because You already defined that rut is primary key, so PKs are always unique (it's PKs behaviour)

2) Define in Your model that rut is primary key, and disable auto incrementing because it's varchar (not int cannot be iterated naturally) :

/**
 * primaryKey 
 * 
 * @var integer
 * @access protected
 */
protected $primaryKey = 'rut'; 
/*
You cannot comment it to make in disabled, it will look for `id` param by default.
You cannot set it to be = null because in Your code You use ::find() function 
that looks for primaryKey.
 */

/**
 * Indicates if the IDs are auto-incrementing.
 *
 * @var bool
 */
public $incrementing = false;

3) Remove this line:

User::create($request->all());

because You're already inserting record to database in previous line.

num8er
  • 18,604
  • 3
  • 43
  • 57
1

The problem was a line of code in the controller. The solution was simply to comment this line:

User::create($request->all());

Thanks for the answers.

Bullgod
  • 149
  • 1
  • 3
  • 15
0

I got it many times with my project. Here it looks you first made a mistake making a table without a Primary Key, then you made it without making unique.
I think you better to check your database tables using a Graphical User Interface, such as MySQL Workbench.

Then make sure your view's input field has the same name attribute as your database column names. That was the main thing I got errors.

{!! Form::text('rut',null,['class'=>'form-control']) !!}
Srneczek
  • 2,143
  • 1
  • 22
  • 26
Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94
  • I check database with mysql workbench, i could't find the error but create another primary key called "id" that works with auto increment option. It worked for error but now two users are created with the same attributes except for the id in the database . The strange thing is that one user has the encrypted password and the other has the password as it was written. – Bullgod Jun 24 '16 at 20:29
  • My form is:
    {!! Form::label('rut') !!} {!! Form::text('rut',null, ['class'=>'form-control','placeholder'=>'Ingresa el rut del usuario']) !!}
    {!! Form::label('nombre') !!} {!! Form::text('nombre',null, ['class'=>'form-control','placeholder'=>'Ingresa el nombre del usuario']) !!}
    {!! Form::label('contrasena') !!} {!! Form::text('contrasena',null, ['class'=>'form-control','placeholder'=>'Ingresa la contraseña del usuario']) !!}
    – Bullgod Jun 24 '16 at 20:31
  • what are 'nombre','contrasena'... they are not database column names.use like {!! Form::text('rut',null, ['class'=>'form-control','placeholder'=>'Ingresa el rut del usuario']) !!} this, here 'rut' is a database table column value. – Sachith Muhandiram Jun 25 '16 at 01:12