How to add a custom validation rule in Laravel? - php

I would like to add custom validations rules on my Laravel Controller:
The container exists in the database
The logged user is owner of the resource
So I wrote this:
public function update($id, Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|unique:stock.containers|max:255'
]);
$container = Container::find($id);
if(!$container)
{
$validator->errors()->add('id', 'Not a valid resource');
}
if($container->owner_id != user_id())
{
$validator->errors()->add('owner_id', 'Not owner of this resource');
}
if ($validator->fails()) {
return response()->json($validator->errors(), 422); //i'm not getting any
}
}
Unfortunately the $validator->errors() or even $validator->addMessageBag() does not work. I noticed $validator->fails() clears the error messages and adding an error will not make the validation to fail.
What is the proper way to achieve this?

Then you can use after:
public function update($id, Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|unique:stock.containers|max:255'
]);
$validator->after(function($validator) use($id) {
$container = Container::find($id);
if(!$container)
{
$validator->errors()->add('id', 'Not a valid resource');
}
if($container->owner_id != user_id())
{
$validator->errors()->add('owner_id', 'Not owner of this resource');
}
});
if ($validator->fails()) {
return response()->json($validator->errors(), 422); //i'm not getting any
}
}

Related

Empty array when passed to response()->json

I have a method in parent class
Controller.php
public function invalidError($errors = [], $code = 422)
{
return response()->json([
'errors' => $errors
], $code);
}
I am passing this method the following:
if($validator->fails()) {
return $this->invalidError([
array('key' => 'Some key')
]);
}
When the response comes in the errors message is always empty array like the following:
{
"errors": []
}
What am I missing?
To get the errors array from a validator, use failed()
if($validator->fails()) {
return $this->invalidError($validator->failed());
}
If you wants the messages from the failed rules use messages()
if($validator->fails()) {
return $this->invalidError($validator->messages());
}
For more information, you can check the documentation

How to solve Trying to get property of non-object in Laravel

I'm a beginner web developer
I'm trying to write a condition that will be fulfilled depending on what data the user will send
Condition if fulfilled by one hundred percent
But the condition else produces an error with the following text
Trying to get property 'unique_id' of non-object
If someone have info how to solv this problem I will be grateful
This is my code from controller
public function checkRestorePassword(Request $request)
{
$result['success'] = false;
$rules = [
'unique_id' => 'required',
];
$validation = Validator::make($request->all(), $rules);
if (empty($validation))
{
$result['error'] = "Enter the code that was sent to you by mail.";
return response()->json($result, 422);
}
$user = User::where('unique_id', $request->uniqueId)->first();
if ($user->unique_id === $request->uniqueId)
{
$result['success'] = 'Access to your personal account successfully restored. Please change your password.';
return response()->json($result, 200);
}
else
{
$result['success'] = false;
return response()->json($result, 422);
}
}
I think it's because $user is returning null.
so do this
if (!is_null($user) && $user->unique_id === $request->uniqueId)

Bad Request (#400) Missing required parameters: id

My Controller:
public function actionCreate()
{
$model = new SuratMasuk(['scenario' => 'create']);
if ($model->load(Yii::$app->request->post()))
{
try
{
$picture = UploadedFile::getInstance($model, 'imageFile');
$model->imageFile = $_POST['SuratMasuk']['id_suratmasuk'].'.'.$picture->extension;
if($model->save())
{
$picture->saveAs('uploads/' . $model->id_suratmasuk.'.'.$picture->extension);
Yii::$app->getSession()->setFlash('success','Data saved!');
return $this->redirect(['view','id'=>$model->id_suratmasuk]);
}
else
{
Yii::$app->getSession()->setFlash('error','Data not saved!');
return $this->render('create', [
'model' => $model,
]);
}
}
catch(Exception $e)
{
Yii::$app->getSession()->setFlash('error',"{$e->getMessage()}");
}
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
getting this error message when i try to save my post. and it just uploads the text not images. i've tried $model->save(false); but not working
i'm newbie on yii, i'll appreciate your help
I guess this is because you try to pass id here:
return $this->redirect(['view', 'id' => $model->id_suratmasuk]);
and since actionView almost for sure requires id as parameter you get this error because $model->id_suratmasuk is empty.
You need to set proper rules() in SuratMasuk model.
Do not use POST variables directly, this is asking for being hacked.
Do not use save(false) if you need to save anything that comes from user (validation is a must!).
Add rules() for all attributes so there will be no surprises like with this id_suratmasuk being empty.
Check result of saveAs() on UploadedFile instance - this can go false as well.

User Roles in Laravel

I want to implement user roles for my controller. When the user is admin or master it works, but when the user is a client it doesn't, and I receive a 205 http response.
This code works nicely in my localhost but it doesn't so in my host.
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
'name' => 'required|string',
'imageone'=> 'required|string'
]);
if ($validation->fails())
{
return response()->json('Fails',404);
}
$user = JWTAuth::parseToken()->authenticate();
if ($user->roles=='admin'||$user->roles=='master') {
$name= $request->input('name');
$imageone = $request->input('imageone');
$cate=new categoryi();
$cate->name=$name;
$cate->imageone=$imageone;
if ($cate->save())
{
return response()->json($cate,202);
}
}
return response()->json('Fails',500);
}

How to format the validation error messages in Laravel 5?

I am building a RESTful API with Laravel 5.1 - When a post request is made, I validate the input, if the input is not valid, I throw an exception.
Current Response Sample:
{
"message": "{\"email\":[\"The email field is required.\"]}",
"status_code": 400
}
How to make my response look like this:
{
"message": {
"email": "The email field is required."
},
"status_code": 400
}
Here's how I throw the exception:
$validator = Validator::make($this->request->all(), $this->rules());
if ($validator->fails()) {
throw new ValidationFailedException($validator->errors());
}
I think the best way to validate the form in laravel is using Form Request Validation .You can overwrite the response method in App\Http\Request.php class.
Request.php
namespace App\Http\Requests;
Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
public function response(array $errors)
{
return $this->respond([
'status_code' => 400 ,
'message' => array_map(function($errors){
foreach($errors as $key=>$value){
return $value;
}
},$errors)
]);
}
/**
* Return the response
*/
public function respond($data , $headers=[] ){
return \Response::json($data);
}
}
You can try this:
$messages = [
'email.required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
Here is a class I use:
<?php
namespace App;
class Hack
{
public static function provokeValidationException($field_messages){
$rules = [];
$messages = [];
foreach($field_messages as $field=>$message){
$rules[$field] = 'required';
$messages[$field. '.required'] = $message;
}
$validator = \Validator::make([], $rules, $messages);
if ($validator->fails()) {
throw new \Illuminate\Validation\ValidationException($validator);
}
}
}
Then any time I need to show custom errors, I do:
\App\Hack::provokeValidationException(array(
'fieldname'=>'message to display',
'fieldname2'=>'message2 to display',
));
I had this same issue and I resolved it by decoding my the $validator->errors() response
return (400, json_decode($exception->getMessage()));

Categories