Get Laravel to return JSON



嗨,我正在努力获取JSON中经过验证的错误消息。我不知道为什么在拉拉威尔这么难做到这一点。我正试图使用ajax请求返回一个包含表单数据错误的HTTP响应。这是我的请求代码

<?php
    namespace AppHttpRequests;
    use AppHttpRequestsRequest;
    use Auth;
    use Log;

    class PostRequest extends Request
    {
        /**
         * Determine if the user is authorized to make $this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }
        /**
         * Get the validation $rules that apply to the request.
         *
         * @return array
         */
    public function wantsJson()
        {
            return true;
        }
    public function response(array $errors) 
       {  
            if ($this->ajax())
           {
                return new JsonResponse($errors, 422);
           }
           return $this->redirector->to($this->getRedirectUrl())
                                        ->withInput($this->except($this->dontFlash))
                                        ->withErrors($errors);
    }
    public function rules() {
      $rules = [];
      foreach($this->request->get('address') as $key => $val) {
        $rules['address.'.$key] = 'required';
      }

     foreach($this->request->get('city') as $key => $val) {
        $rules['city.'.$key] = 'required';
      }
  return $rules;
   }

 public function messages() {

  foreach($this->request->get('address') as $key => $val) {

    $messages['address.'.$key.'.required']="*Please fill in the address";
          } 
        foreach($this->request->get('city') as $key => $val) {

             $messages['city.'.$key.'.required']="*Please fill in the city";
         } 
          return  $messages;
          }
                }

这是我的控制器代码

  namespace AppHttpControllers;
  use IlluminateHttpRequest;
  use AppHttpRequests;
  use AppHttpRequestsPostRequest;
  use Auth;
  class propContoller extends Controller {

     public function __construct() {
           $this->middleware('auth');
     }

     public function main ()  {
             $amount = Auth::user()->units;   // pull amount of units from data base and create forms 
           return view("myprop",compact("amount"));
     }
     public function Postdata(PostRequest $request) {


      }
  }

和我的ajax请求

$("#from").submit(function(event) {
$.ajax({
  type: 'post',
  url: '/myproperties/save',
  data: { '_token': token, 'data': "good" },
  dataType: 'json',
  success: function(data){
  console.log(data);
  },
  error: function(data){
    var errors = data.responseJSON;
    console.log(errors);
    // Render the errors with js ...
  }
});

和我的HTML

       <div  class="form-group col-md-6">

                <div  class= "col-md-6  form-group {{ $errors->has('address.'.$i) ? ' has-error' : '' }}">
            <label for={{$id = "Address".$i}}>Address</label>
              <input  value="{{ old('address.'.$i) }}" type="text"  name="address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address">

              @if ($errors->has('address.'.$i))
                          <span class="help-block">
                          <strong>{{ $errors->first('address.'.$i) }}</strong>
                              </span>
                 @endif
                </div>
<div  class="col-md-6 form-group {{ $errors->has('city.'.$i) ? ' has-error' : '' }}">
           <label for={{$id = "city".$i}}>City</label>
            <input value="{{ old('city.'.$i) }}" type="text"  name="city[{{$i}}]"  class="form-control" id={{$id = "City".$i}} placeholder="City">
             @if ($errors->has('city.'.$i))
                       <span class="help-block">
                           <strong>{{ $errors->first('city.'.$i) }}</strong>
                            </span>
                        @endif
                  </div>

请有人帮我,我不想拉拉威尔,所以对我宽容一点

谢谢!

你错了。在Laravel中创建JSON响应非常容易,这样以后,您的前端玩具就可以使用它了

public function getSomethingById(string $id)
{
    $data = $this->fooRepository
        ->getSomething($id)
        ->pluck('name', 'id')
        ->toArray(); // you don't have to use repository, you can use Eloquent directly here, or DB facade or even hardcode the array.
    return response()->json([
        'count' => count($data),
        'data' => $data // or whatever
    ]);
}

无论您需要什么,只要记住response()->json()需要一个数组。Laravel将返回具有正确mime类型的JSON响应。

然后您可以使用jQuery来$.get()您的AJAX资源等。

这就是返回json的方式,它在laravel 中非常容易

if($request->ajax()){
    return response()->json($something);
}
else
{
//return View or whatever
}

最新更新