dongshi8038 2016-11-15 16:34
浏览 113

将Laravel验证错误返回给Ajax调用

I'm trying to figure out how to pass back to my ajax call that there were validation errors if there is so that I can prevent the page from continuing on and display those errors to the user.

/*
* Create User After they complete the first part of the form. 
*
*/
public function createUserAndOrder(Request $request)
{
    $validation = $this->validate($request, [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|confirmed|unique:users,email',
        'email_confirmation' => 'required'
    ]);

    $credentials = [
        'first_name' => $request->input('first_name'),
        'last_name' => $request->input('last_name'),
        'email'    => $request->input('email'),
        'password' => Hash::make(str_random(8)),
    ];

    $user = Sentinel::registerAndActivate($credentials);

    $user->role()->attach(5);

    return response()->json([
        'success' => true,
        'errors' => null
    ]);
}
  • 写回答

1条回答 默认 最新

  • drt96856 2016-11-15 16:42
    关注

    You can try it by using Validate Facade as:

    $validator = \Validator::make($request->all(), [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|confirmed|unique:users,email',
        'email_confirmation' => 'required'
    ]);
    
    // Validate the input and return correct response
    if ($validator->fails())
    {
        return response()->json(array(
            'success' => false,
            'errors' => $validator->getMessageBag()->toArray()
    
        ), 422);
    }
    

    This would give you a JSON response like this:

    {
        'success': false,
        'errors': {
            'first_name': [
                'The first name field is required.'
            ],
            'last_name': [
                'The last name field is required.'
            ]
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘