500(内部服务器错误) - 用户注册系统 - Laravel

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (31)

所以,基本上我试图在Laravel中创建一个用户注册系统。注册表单验证效果很好,但在验证通过后我无法插入数据。相反,我得到了这个错误。任何帮助,将不胜感激。谢谢!

我试图使用查询构建器来插入数据。不幸的是,它仍然无效。

寄存器的script.js

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(document).ready(function () {
    $('#btnRegister').click(function (e) {
        e.preventDefault();
        $.ajax({
            url: "/validate-register",
            type: "post",
            data: {
                email: $('#exampleInputEmail1').val(),
                username: $('#exampleInputUsername1').val(),
                password: $('#exampleInputPassword1').val(),
                confirmPassword: $('#exampleInputConfPassword1').val()
            },
            error: function (data) {
                var errMsg = "";
                var response = JSON.parse(data.responseText);
                Object.keys(response.errors).forEach(function(k){
                    errMsg += '<li>' + response.errors[k] + '</li>'
                }) ;
                $('body').css({'overflow': 'visible'});
                $('.alert').css({'display': 'block'});
                $('.alert-danger').html(errMsg);
            },
            success:function(data){
                window.location.href = '/';
            }
        });
    });
});

寄存器Controller.php这样

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use App\UserModel;

class RegisterController extends Controller
{
    public function Index(){
        return view('register');
    }

    public function ValidateRegister(Request $req){

        $validatedData = $req->validate([
            'email' => 'required|email',
            'username' => 'required',
            'password' => 'required|min:6',
            'confirmPassword' => 'required|same:password'
        ]);   
        if(!$validatedData->fails())
            insertNewUser($validatedData['email'],$validatedData['username'],Hash::make($validatedData['password']));
    }

    public function insertNewUser($email, $username, $password){        
        DB::table('users')->insert([
            'email' => $email,
            'username' => $username,
            'password' => $password
        ]);

        return response()->json(['response' => 'success']);
    }
}

错误消息:

POST http://127.0.0.1:8000/validate-register 500 (Internal Server Error)

Uncaught TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.error (register-script.js:22)
    at u (app.js:1)
    at Object.fireWith [as rejectWith] (app.js:1)
    at C (app.js:1)
    at XMLHttpRequest.<anonymous> (app.js:1)
提问于
用户回答回答于

我没有尝试,但我认为当你使用$request->validate([rules...])它时不会返回验证器对象,而是返回已经验证为数组的字段。

所以你的控制器方法应该成为:

public function ValidateRegister(Request $req)
{
    $validatedData = $req->validate([
        'email' => 'required|email',
        'username' => 'required',
        'password' => 'required|min:6',
        'confirmPassword' => 'required|same:password'
    ]);

    return $this->insertNewUser(
        $validatedData['email'],
        $validatedData['username'],
        Hash::make($validatedData['password'])
    );
}

validate方法本身通过将错误作为响应返回来处理失败的验证

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励