0

When you validate your data using a request service how do you return the the errors in json format like e.g.

return response->json(array("errors' => true, 'errors' => $errors));

Request Service:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Auth;

class MyRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    protected $action;

    public function authorize()
    {
        if(Auth::check()) {
            return true;            
        }        
    }

    public function validate() {
        return parent::validate();
    }

    public function all()
    {

    }

    public function messages()
    {
    }    

    public function rules()
    {               

    }
}

Controller:

public function store(MyRequest $request) {
    $mymodel = new MyModel();
    $mymodel->title = 'test';
    $model->save();
}
ONYX
  • 5,679
  • 15
  • 83
  • 146

1 Answers1

1

You don't have to do it manually, it will automatically sends an errors response, which could be use like:

    @if ($errors->has())
      <div class="alert alert-danger">
        @foreach ($errors->all() as $error)
           {{ $error }}<br>        
        @endforeach
      </div>
    @endif

OR

@if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif

OR

Skip Request and do Validator::make() and in the end do:

return response($validatorObject->messages(), 500);
Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
  • Isn't that a server side validation response, I want to format the response as json – ONYX May 05 '16 at 06:06
  • 1
    If you're using Laravel Request for validation then it's a server side validation. While you submit the form the validation and response is been handled automatically and you wont be able to dictate the response. Which leads to 2 ways, either you do `Validator::make` and make your own response (json) or you can do `json_encode($errors)`. Whichever way you're comfortable. – Gaurav Dave May 05 '16 at 06:11
  • So are you saying that if I use a request service I can't format that response. – ONYX May 05 '16 at 06:14
  • I've found this link: http://stackoverflow.com/questions/31507849/how-to-force-formrequest-return-json-in-laravel-5-1. and you can change the response in json. Here, you have to override laravel fuctionality. Which I think as an overkill. – Gaurav Dave May 05 '16 at 06:28
  • I went to that link and used the function wantsJson my question now is how do you know that the response is an error cose it just returns an object – ONYX May 05 '16 at 06:51