SeanDp32
SeanDp32

Reputation: 309

Get Laravel to return 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 !

Upvotes: 3

Views: 3758

Answers (2)

Matt Komarnicki
Matt Komarnicki

Reputation: 5422

You're wrong. It's extremely easy to create JSON response in Laravel so that later, your frontend toys can use it.

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
    ]);
}

Whatever you need, just remember that response()->json() expects an array. Laravel will return JSON response with proper mime type.

Then you can use jQuery to $.get() your AJAX resource etc.

Upvotes: 3

Achraf Khouadja
Achraf Khouadja

Reputation: 6269

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

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

Upvotes: 3

Related Questions