weixin_33709219 2016-05-09 23:50 采纳率: 0%
浏览 111

获取Laravel返回JSON

Hi am struggling to get my validated error messages in JSON. I don't know why it is so hard to do this in laravel. I am trying to use a ajax request to get back a HTTP response with my form data errors. Here is my request code

<?php

    namespace App\Http\Requests;

    use App\Http\Requests\Request;

    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;

          }

                }

Here is my controller code

  namespace App\Http\Controllers;

  use Illuminate\Http\Request;

  use App\Http\Requests;

  use App\Http\Requests\PostRequest;

  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) {





      }
  }

and my ajax request

$("#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 ...
  }

});

and my 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>

Some one please help I am noob to laravel so go easy on me

Thank you !

  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 Android URL如何转成视频/音频,可行吗?
      • ¥20 SQL数据查询,子查询
      • ¥15 c++字符串分割问题
      • ¥15 关于#sql#的问题:没有用命令关闭cdc,手动把系统表开启的cdc右键删除了
      • ¥15 vue+uniapp
      • ¥15 android freedom
      • ¥15 使用自定义的类型代替内置类型可行吗
      • ¥15 关于STM32的SPI和ENDAT接口编码器通信的问题
      • ¥15 关于#pdfbox#生成的PDF文件正常,转图片中文乱码的问题,如何解决?
      • ¥15 ADS中有关DAC控件的使用问题