如何从laravel与json数据库中获取数据


how to get data from database in laravel with json?

我正试图使一个验证在ajax如果电子邮件已经采取了laravel 5。

这是我的ajax:

$.ajax({
    type: 'POST',
    url: '/EditEmail',
    data: form.serialize(),
    dataType: 'json',
    timeout: 9000,
    error:function(data) {
        //verify if the user has already been taken 
    },
    success:function(data) {
        window.location.href=window.location.href;
    }   
});

这是我的控制器中的代码:

public function EditEmail()
{    
    if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
    {
       DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));
       return Response::json(['success' => 'request succeeded'], 200);
    }    
}

所以我已经在我的控制器和用户不能引入相同的电子邮件验证,但我想知道我如何能从我的控制器发送数据到ajax,所以我可以在那里验证了。谁有解决办法?

您有两个选择。

第一个选项使用statusCode:

根据Ajax文档(http://api.jquery.com/jQuery.ajax/),您可以这样做:
statusCode: {
    200: function() {
      alert( "user found" );
    },
    404: function() {
      alert( "user not found" );
    }
 }

并在控制器中返回:

// user does not exist
return Response::json(['status' => 'not_found'], 404);
//or if the user does exist
return Response::json(['status' => 'found'], 200);

第二个选项使用简单的json数据:

$.ajax({
   type: 'POST',
    url: '/EditEmail',
    data: form.serialize(),
    dataType: 'json',
    timeout: 9000,
    error:function(data) {
       //something went wrong with the request 
    },
    success:function(data) {
        if(data['status'] == "found") {
             alert( "user found" );
        } else {
             alert( "user not found" );
        }
    }   
});

在你的控制器中:

public function EditEmail()
{    
     if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
     {
          DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));
          return Response::json(['status' => 'not_found']);
     }    
     return Response::json(['status' => 'found']);
}