2

I try to create some API and add custom validation:

controller :

use App\Http\Requests\Penggunarequest;

class LogRegAPI extends Controller {  


    public function register(Penggunarequest $penggunarequest) {
        $input = $penggunarequest->all();
        $nama = $input['name'];
        $alamat = $input['address'];
       //other logical thing  

validation request :

namespace App\Http\Requests;

use App\Http\Requests\Request;

class Penggunarequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|String',
            'address' => 'required|String',                
        ];
    }
}

If i send post data via controller by using browser, it will redirect to form post if have error response, but I want to post it via android, evertything work well except if it have error response it display 302. How to make error response show in custom JSON?

2 Answers 2

2

I just found the answer, I just need to override the request class. By adding bellow code on my form request validation

public function wantsJson()
    {
        return true;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

https://laracasts.com/series/digging-in/episodes/8 is a good example. You can put the validation rules in the model, and then on your controller have something like this:

            $this->model->setRawAttributes($request->all());

            if (!$this->model->save()) {
                return $this->response($this->model->getErrors(), 409);
            }

            return $this->model;

You could then make a middleware controller, and check if it is a JSON header response, and convert to JSON on the fly for it. This way the validation links to the data, and the controller doesn't have to care about JSON.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.