0
public function store(Request $request) {

        $response = array('response' => '', 'success'=>false);

        $rules = [
            'email' => 'required|email',
            'password' => 'required'
        ];

        $validator = \Validator::make($request->all(), $rules);

        if($validator->fails()){
            $response['response'] = $validator->messages();
            return $this->response->error($response, 401);
            // or
            return $this->response->error($validator, 401);

        }else{
            User::create($request->all());  
        }

    }

How can I set validator in laravel using dingo API? I tried above code but does not work can't understand where is the right reference to keep track error logs

Please guide.

Aftab H.
  • 1,517
  • 4
  • 13
  • 25

3 Answers3

1
$rules = [
        'username' => 'required',
        'password' => 'required'
    ];

    $payload = app('request')->only('username', 'password');

    $validator = app('validator')->make($payload, $rules);

    if ($validator->fails()) {
        throw new Dingo\Api\Exception\StoreResourceFailedException('Invalid username provided.', $validator->errors());
    }

You can try this

Shunhra Sarker
  • 187
  • 1
  • 2
  • 15
0
public function store() 
{
     $rules = [
        'email' => 'required|email',
        'password' => 'required'
    ];


    $payload = app('request')->only('username', 'password');

    $validator = app('validator')->make($payload, $rules);

    if ($validator->fails()) {
        throw new Dingo\Api\Exception\StoreResourceFailedException('Could not create new user.', $validator->errors());
    }

    User::create($request->all());

    // send a success response
}

This example is taken from the documentation of Dingo and customized based on your code.

common sense
  • 3,775
  • 6
  • 22
  • 31
0

The best way I've found to do validation especially when using Dingo API is to use Form Requests.

When using Dingo API however, you use

use Dingo\Api\Http\FormRequest;

instead of

use App\Http\Requests\Request; like in normal form requests.

So in your case, you'd have a form request like

<?php

namespace App\Http\Requests;

use Dingo\Api\Http\FormRequest;

class CreateUser extends FormRequest
{
    /**
     * 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 rules()
    {
        return [
            'email' => 'required|email',
            'password' => 'required'
        ];
    }
}

So this keeps validations outside your controller. And your controller function can just be

public function store(Request $request) {
      User::create($request->all());  
}

If you are not very familiar with Form Requests, this is a great chance to look at it. Cheers.

AceKYD
  • 1,100
  • 1
  • 10
  • 14