-1
我的Laravel應用程序出現了一個奇怪的問題,一旦驗證規則啓動,此代碼被調用兩次。我將驗證邏輯抽象爲一個單獨的類,但不管我如何使用該API(使用郵差試過了,用jQuery)仍出現與輸出看起來像這樣運行兩次:Laravel請求使用自定義valiation類發射兩次
called{"email":["The email has already been taken."],"country":["The country must be a number."]}called{"email":["The email has already been taken."],"country":["The country must be a number."]}
我只期待一個JSON響應。我正在撕掉我的頭髮,嘗試了兩個不同的連接,似乎無法解決爲什麼自定義請求被調用兩次。這是一個新的Laravel應用程序,所以沒有太多的代碼與它衝突。任何想法讚賞。
//Create User Request extends standard request. Handles Validation
public function __construct(CreateUserRequest $request){
$this->request = $request;
}
public function register()
{
try{
$array = DB::transaction(function(){
$email = $this->request->input('email');
$password = $this->request->input('password');
$companyName = $this->request->input('companyName');
$userName = $this->request->input('name');
$country = $this->request->input('country');
$company = Company::create([
'name' => $companyName,
'active'=>true,
'country_id'=>$country
]);
$user = User::create([
'company_id' => $company->id,
'name'=>'admin',
'email' => $email,
'password' => $password,
'active' =>true
]);
if(!$company || !$user)
{
throw new \Exception('User not created for account');
}
return compact('company', 'user');
});
$token = JWTAuth::fromUser($array['user']);
return Response::json(compact('token'));
}
catch(Exception $e)
{
return Response::json(['error' => $e->getMessage() ], HttpResponse::HTTP_CONFLICT);
}
}
然後驗證定製請求..
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Response;
class CreateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
public function response(array $errors)
{
// return Response::json(['errorg' => $errors ], 200);
echo('called');
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => 'required|unique:users',
'password' => 'required',
'companyName' => 'required',
'name' => 'required',
'country' => 'required|numeric'
];
}
}
傳說!這工作任何想法是什麼做? – Paul
那麼,請求類被用來處理每個方法的請求,而不是每個控制器。 我認爲第一次請求類是在__construct()上觸發的,另一個是對方法的實際請求觸發的。實際上不確定。 –
@Paul請在使用SO之類的懶惰方法之前先閱讀文檔。 – Kyslik