How to validate without request in Laravel - php

I need to validate an array but without a request.
In laravel docs validation is described like this:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
But I can't use $request because the data comes from an external api and the validation is not inside a controller. How can I validate this array? For example:
$validatedData = validate([
'id' => 1,
'body' => 'text'
], [
'id' => 'required',
'body' => 'required'
]);

Should be. Because $request->all() hold all input data as an array .
$input = [
'title' => 'testTitle',
'body' => 'text'
];
$input is your custom array.
$validator = Validator::make($input, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);

Validator::make expects array and not a request object.
You can pass any array and implements the rules on it.
Validator::make(['name' => 'Tom'], ['name' => 'required', 'id' => 'required']);
And it will validate the array. So $request object is not necessary.

You can achieve this by create request object like so:
$request = new Request([
'id' => 1,
'body' => 'text'
]);
$this->validate($request, [
'id' => 'required',
'body' => 'required'
]);
and thus you will get all the functionality of the Request class

$request->all() is array not request object.
This code will work:
$data = [
'id' => 1,
'body' => 'text'
];
$validator = Validator::make($data, [
'id' => 'required',
'body' => 'required',
]);

You can also merge data with the request object:
$data = ['id' => 1];
$request->merge($data);
Then validate as per usual.

Related

Add new Object data Using PHP Laravel (Array_push)

Array one:
[
'jabatan' => 'required',
'tipe_kegiatan' => 'required',
'waktu' => 'required',
'nrt' => 'required',
0 => [
'materi' => 'required',
'metode' => 'required',
'hasil' => 'required',
'img' => 'required|image|max:1024',
]
];
Array two:
[
'jabatan' => 'required',
'tipe_kegiatan' => 'required',
'waktu' => 'required',
'nrt' => 'required',
'materi' => 'required',
'metode' => 'required',
'hasil' => 'required',
'img' => 'required|image|max:1024',
];
how to change the data array as shown below
Change Data array one to array two (I try using array_push but I don't get the wanted result)
My case:
I have 2 conditions where if the user inputs by selecting form type 1 then the validation will adjust to form 1 and if the user selects input with form 2 then the validation also adjusts to form 2. all processes are in one post request action.
you should use array_merge like this:
<?php
$a1=["red","green"];
$a2=["blue","yellow"];
print_r(array_merge($a1,$a2));
?>

laravel validation error when trying to update

When I try to update a post if I dont change value of slug , laravel return this error:
The slug has already been taken.
Here is my validation:
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required | unique:providers'
]);
when you're updating records and there is unique validation is added. You should pass the id of which record you're inserting.
While Update
'slug' => 'required | unique:providers,slug,'.$providerId
While insert
'slug' => 'required | unique:providers'
You need to add an except rule to your unique case to exclude the current ID from check:
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required|unique:providers,id,' . $provider->id
]);
Make the column and the id that you pass to use your table's data. I am just giving you an idea on what you need to add.
You need to tell the validator to do an exception for the current entity you're updating.
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required|unique:providers,slug,'.$providerId
]);
When adding:
use Illuminate\Support\Str;
.
.
$slug = Str::slug($request->name, '-');
$exists = Provider::where('slug', $slug)->first();
if($exists) {
$slug = $slug.'-'.rand(1000,9999);
}
When updating:
$request->validate([
'slug' => 'required|unique:providers,slug,'.$provider_id.',id',
]);

Returning Laravel validation errors to Ajax call

I'm trying to figure out how to pass back to my ajax call that there were validation errors if there is so that I can prevent the page from continuing on and display those errors to the user.
/*
* Create User After they complete the first part of the form.
*
*/
public function createUserAndOrder(Request $request)
{
$validation = $this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|confirmed|unique:users,email',
'email_confirmation' => 'required'
]);
$credentials = [
'first_name' => $request->input('first_name'),
'last_name' => $request->input('last_name'),
'email' => $request->input('email'),
'password' => Hash::make(str_random(8)),
];
$user = Sentinel::registerAndActivate($credentials);
$user->role()->attach(5);
return response()->json([
'success' => true,
'errors' => null
]);
}
You can try it by using Validate Facade as:
$validator = \Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|confirmed|unique:users,email',
'email_confirmation' => 'required'
]);
// Validate the input and return correct response
if ($validator->fails())
{
return response()->json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 422);
}
This would give you a JSON response like this:
{
'success': false,
'errors': {
'first_name': [
'The first name field is required.'
],
'last_name': [
'The last name field is required.'
]
}
}

laravel 5.2 set attribute name

How i set custom the attributte names in laravel 5.2 I already try this code, but doesn't work:
$attNames = array(
'code' => 'Número',
'contributor' => 'Nº Contribuinte',
'create_date' => 'Data criação',
'address' => 'Morada',
'zip_code' => 'Cod. Postal',
'city' => 'Localidade',
'email' => 'E-mail',
'phone_number' => 'Telefone',
'note' => 'Observações',
);
$validator = Validator::make($client, $this->rules,[],$attNames);
$validator->setAttributeNames($attNames);
if ($validator->fails()) {
// send back to the page with the input data and errors
$errors = $validator->messages();
return Redirect::to('/client/create')->withInput()->withErrors($errors);
}
You have passed wrong arguments to Validator::make.
You can pass only three arguments.
As per Documentation,
If needed, you may use custom error messages for validation instead of
the defaults. There are several ways to specify custom messages.
First, you may pass the custom messages as the third argument to the
Validator::make method.
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
I figure out.
controller:
use Validator;
(...)
$attName=array(
'code' => trans('validation.code'),
'contributor' => trans('validation.contributor'),
'create_date' => trans('validation.create_date'),
'address' => trans('validation.address'),
'zip_code' => trans('validation.zip_code'),
'city' => trans('validation.city'),
'email' => trans('validation.email'),
'phone_number' => trans('validation.phone_number'),
'note' => trans('validation.note'),
);
$validator = Validator::make($client, $this->rules, [], $attNames);
validation.php:
'attributes' => [
'code' => 'número',
'contributor' => 'nº contribuinte',
'create_date' => 'data criação',
'address' => 'morada',
'zip_code' => 'cod. postal',
'city' => 'localidade',
'email' => 'e-mail',
'phone_number' => 'telefone',
'note' => 'observações',
],

Laravel routing to controller - routing to wrong route

I have a very strange bug.
Running Laravel 4.1 as my company hasn't upgraded their PHP version yet.
The routes file has this:
Route::controller('survey', 'SurveyController');
And, when you go to /survey/new-survey it ends up being sent to postNewQuestion function instead of postNewSurvey.
public function postNewSurvey() {
$input = Input::all();
//dd($input);
$rules = array(
'name' => 'required|unique:lime_surveys_languagesettings,surveyls_title',
'language' => 'required'
);
...... etc
}
public function postNewQuestion() {
$input = Input::all();
//dd($input);
$rules = array(
'sid' => 'required',
'gid' => 'required',
'type' => 'required',
'question' => 'required',
'mandatory' => 'required',
);
$validator = Validator::make($input, $rules);
if($validator->fails()) {
return Response::json(array('success' => false, 'error' => 'validation',
'messages' => $validator->messages(), 'failed' => $validator->failed()));
}
......... etc
}
Thanks.

Categories