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

获取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条回答 默认 最新

  • 旧行李 2016-05-10 00:29
    关注

    This is how you return json , its realy easy in laravel

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

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用