Laravel API - Display all districts when state field is empty - laravel

Below given is my code to display the specific districts of an inputted state. But in this code itself, i want to display all districts in the db if the state field is empty. How to modify my code to get such an output. So, my desired API works such that it returns all the districts when the api is called. And only if the state field is inputted, it shows the particular districts specific to it. Help me with ur suggestions.
public function state_lookup(Request $request)
{
$validator = Validator::make
($request->all(),
[
'state' => 'string',
]
);
if ($validator->fails()) {
return response()->json(
[$validator->errors()],
422
);
}
if(empty($request->state)){
$dist=PersonalDetails::get(['district']);
return response()->json($dist);
}
$data = PersonalDetails::where('state',$request->state)->get(['district']);
// dd($data);
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
else{
return response()->json(['message'=>'Invalid State']);
}
}
in failure case,I am getting json result as below
{
"message": "success",
"data": []
}
it shows "success" instead of "invalid state"

You can use when
$data = PersonalDetails::when(!empty($request->state),function ($query)use($request){
$query->where('state',$request->state);
})->get(['district']);
or
$data = PersonalDetails::where(function ($query)use($request){
if(isset($request)&&!empty($request)){
$query->where('state',$request->state);
}
})->get(['district']);
To avoid 0 key in response change like below
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}

Try with this,
//In your controller
$request->validate([
'state' => 'string'
]);
// $request->validate it self return error messages you have to display
// for an example (write below code in your blade file)
#error('state')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
// write below code in your controller file
$details = PersonalDetails::select('district');
$details->where(function($query) use($request) {
if (isset($request->state) && $request->state != '') {
$query->where('state', $request->state);
}
// do what you want to filter in your query like above
});
$data = $details->get();

Related

Make request (pass data) from Command File to Controller in Lumen/Laravel

i get data (query) in command file and want to pass to controller via API (route)
here my request code in command file :
$request = Request::create('/create_data_account', 'post', ['data'=>$data]);
$create = $app->dispatch($request);
this is the route :
$router->post('/create_data_account', 'APIController#create_account_data_api');
and my controller :
public function create_account_data_api(Request $request)
{
$count = 0;
foreach ($data as $key => $value) {
$insert = Account::create([
'account_name' => $value->account_name,
'type' => $value->type,
'role_id' => $value->role_id
]);
if($insert){
$count++;
}else{
return $response = ['result'=>false, 'count'=>$count, 'message'=>'Internal error. Failed to save data.'];
}
}
return $response = ['result'=>true, 'count'=>$count, 'message'=>'Account data saved Successfully'];
}
i'm confused why passing data to controller not working with that code. anyone can give me solution ? Thanks
As you are making the request with ['data'=>$data]. That means all the data is contained on the key data of your array. So before the foreach loop, you need to add a declaration statement $data = $request->input('data'); to get data in $data variable.

How to reinitialize model when client side validation fails in Yii 2?

I am working on Yii 2 form and I want to reinitialize model when client side validation fails. For example with certain rules like below:
public function rules()
{
return [
[['username'], 'required', 'message' => 'You must enter your username'],
['username','email'],
[['password'], 'required', 'message' => 'You must enter your password'],
];
}
When validation fails I want all fields to be empty (for example when user enters invalid email address). How can I do that?
I assume you use standard Yii 2 way of loading the model:
$model = new SomeModel();
if ($model->load(\Yii::$app->request->post()) && $model->save()) {
// ...
}
return $this->render('view', ['model' => $model]);
Set fields to null when validation fails. You don't want to create new instance (which would be easier) because you would lost all validation messages.
$model = new SomeModel();
if ($model->load(\Yii::$app->request->post())) {
if ($model->save()) {
// ....
} else {
$model->username = null;
$model->password = null;
}
}
return $this->render('view', ['model' => $model]);
UPDATE: for the client side validation add this JS code in view:
$("#form-ID").on("afterValidateAttribute", function (event, attribute, messages) {
if (event.result === false) {
attribute.value = "";
}
});
Replace #form-ID with proper form element JS identifier.

Updates records more than one time on laravel

I am trying to update values in laravel. I have a userupdate profile api which I can update the values first time with given parameters and their values but 2nd time when I update same values it gives me user profile does not exist.
My Code is :
public function UpdateUserProfile(Request $request)
{
$id = $request->input('id');
$client_gender = $request->input('client_gender');
$client_age = $request->input('client_age');
$client_weight = $request->input('client_weight');
$client_height = $request->input('client_height');
$client_dob = $request->input('client_dob');
$profile= DB::table('clients')
->where('id',$id)
->update(['client_gender'=>$client_gender,'client_age'=>$client_age,'client_height'=>$client_height,'client_weight'=>$client_weight,'client_dob'=>$client_dob]);
if($profile)
{
$resultArray = ['status' => 'true', 'message' => 'User profile updated Successfully!'];
return Response::json( $resultArray, 200);
}
$resultArray = ['status' => 'false', 'message' => 'User profile does not exist!'];
return Response::json($resultArray, 400);}
first time when I update the value it gives me the response like this:
{
"status": "true",
"message": "User profile updated Successfully!"
}
and when I hit the update request through a postman it gives a 400 Bad request and response is :
{
"status": "false",
"message": "User profile does not exist!"
}
I'd recommend rewriting that function to look like the following; mostly because it reads better and uses the Model methods that are more commonly found in Laravel
public function UpdateUserProfile(Request $request)
{
// this code fails if there is no client with this id
$client = App\Client::findOrFail($request->id);
// attach new values for all of the attributes
$client->client_gender = $request->input('client_gender');
$client->client_age = $request->input('client_age');
$client->client_weight = $request->input('client_weight');
$client->client_height = $request->input('client_height');
$client->client_dob = $request->input('client_dob');
// save
$client->save();
return ['status' => 'true', 'message' => 'User profile updated Successfully!'];
}

Why I am getting error message when using Yii CActiveForm::validate() with array

I have a problem related to CActiveForm::validate(). I have a form and and sending data to database using Ajax, my form contains a multiple selectable drop-down list. In data saving section of controller produced the following error initially
mb_strlen() expects parameter 1 to be string, array given (.../framework/validators/CStringValidator.php:84)
and after updating framework to newer version, that error gone, and got the below validation message instead.
Category Ids is invalid.
If the form is fully filled(I mean all the rules in the model satisfied), it will not produce any such bug or error message.
controller action
public function actionCompany() {
$model = new Company;
if (isset($_POST['Company'])) {
$model->attributes = $_POST['Company'];
$category_ids = "";
if (is_array($_POST['Company']['category_ids']))
$category_ids = implode(',', $_POST['Company']['category_ids']);
$model->category_ids = $category_ids;
if ($model->validate()) {
/*$temp = Company::model()->findByPK($model->id);
if ($temp !== null) {
$model = $temp;
}*/
$model->save();
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate($model);
if ($error != '[]')
echo $error;
}
}
}
Model rules
public function rules()
{
return array(
array('...., category_ids,...', 'required'),
array('..., category_ids, ...', 'length', 'max'=>255),
....
.....
array('...., category_ids,...', 'safe', 'on'=>'search'),
);
}
What is actually I'm missing?
By default, CActiveForm::validate($model) loads the model attributes from $_POST and overrides current attribute values, thus destroying your transformed values. Pass false as the third argument to avoid this.

parsing arguments with Codeigniter form_validation callback for file input

I have a upload input and am trying to parse an argument to callback function via the CI form_validation library.
$this->form_validation->set_rules('orderfile', 'Order Form'," trim|callback_upload_check[$account_id]");
This calls:
public function upload_check($str, $id)
{
$errors = $this->do_upload($id);
if(isset($errors['error']))
{
$this->form_validation->set_message('upload_check', $errors['error']);
return FALSE;
}else{
return TRUE;
}
}
The Codeigniter Userguide states that when calling the function, the first argument is parsed as the second argument inside the function.
Neither arguments are parsed through. I found this post on the Codeigniter Forum
This seems to explain what is happening (variables are stripped). If i change the to <input type="text" /> the params work...
Is there anyway of getting around this problem?
you need to edit your code like this :
$this->form_validation->set_rules('orderfile', 'Order Form'," trim|callback_upload_check[".$account_id."]");
i also noticed that in your form_validation->set_rules you are not passing any value for id so in your function you should do :
public function upload_check($str, $id=0){..}
You need to change the function to:
public function upload_check($orderfile)
{
$errors = $this->do_upload($orderfile);
if(isset($errors['error']))
{
$this->form_validation->set_message('upload_check', $errors['error']);
return FALSE;
}else{
return TRUE;
}
}
I know this is an old question, but I was having the same problem, I finally realized the second parameter comes back in quotes, so if you pass an $id with the value 1, it actually comes back as "1".
So, to the original question, you need to callback the function like so:
$this->form_validation->set_rules('orderfile', 'Order Form'," trim|callback_upload_check[".$account_id."]");
And in your call back function:
public function upload_check($str, $id){
$actual_id=str_replace('"', "", $id)
}
$config =array(
array(
"field" => "userEmail",
"label" => ":userEmail:",
"rules" => "required|valid_email",
),
array(
"field" => "userPassword",
"label" => ":userPassword:",
"rules" => "required|min_length[8]",
),
);
$error_messages = array(
"required" => "{field} the field is required.",
"min_length" => "{field} the field value is so short",
"valid_email" => "{field} please valid email",
);
$this->form_validation->set_message($error_messages);
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE) {
$alert =preg_replace("/(\n)+/m", ' ', strip_tags(validation_errors()));
$explode =explode(':', $alert);
$arr =array();
for($i=1; $i < count($explode); $i+=2){
$y=$i;
$j =++$y;
$arr[$explode[$i]] = $explode[$j];
}
print json_encode($arr);
} else {
//process
}

Resources