Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API in Laravel when validating the request

I'm currently trying out on how to build a RESTful API with Laravel and I'm currently in the process of creating a new user. This is just a test and I'm getting some result when trying to validate the request using validation in Laravel; here is the result:

enter image description here

I've been trying to create a new one by this code:

public function store() {      $validation = Validator::make(Request::all(),[          'username' => 'required|unique:users, username',         'password' => 'required',     ]);      if($validation->fails()){       } else{             $createUser = User::create([                 'username' => Request::get('username'),                 'password' => Hash::make(Request::get('password'))              ]);     } } 

but then I don't know how to return the error in validation. But it keeps on giving me that HTML as showed in the image when I was trying to do the if with validation->fails(). Is there a way to get the validation in JSON format?

like image 507
Aoi Avatar asked Apr 18 '14 21:04

Aoi


People also ask

How do I validate in laravel?

Validation is the most important aspect while designing an application. It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.


1 Answers

these code will help you, working for me.

$response = array('response' => '', 'success'=>false); $validator = Validator::make($request->all(), $rules);  if ($validator->fails()) {   $response['response'] = $validator->messages(); } else { //process the request }  return $response; 
like image 145
bhupendraosd Avatar answered Sep 21 '22 19:09

bhupendraosd