How to decrypt string only if string is not null/empty - php

I have a form which a user can come back to and complete at any time. I have one select box in particular with data which needs to be encrypted.
The issue I am having is that because this field is optional, there are times when the field can be null/empty and therefore my page fails with the error "The payload is invalid." I am assuming this is because it is trying to decrypt a field which is null and therefore it cannot.
Here is part of the blade below:
<label for="religion">Religion</label>
<select class="form-control" name="religion" id="religion">
<option value="" selected>Choose...</option>
<option value="Religion 1" #if(old('religion', decrypt($user->diversity->religion) === "Religion 1")) selected #endif>Religion 1</option>
<option value="Religion 2" #if(old('religion', decrypt($user->diversity->religion) === "Religion 2")) selected #endif>Religion 2</option>
</select>
Because I am also using the old() function to also return the values of the fields if validation fails, I can't do an if statement with empty() to check if $user->diversity->religion is not empty.
Is there a way of doing this without making my blade too bloated. It would be ideal if there was a way to only decrypt a string if it isn't empty/null.

Just check if the value is empty before passing it to decrypt:
<option value="Religion 1" #if(old('religion', empty($user->diversity->religion) ? '' : decrypt($user->diversity->religion) === "Religion 1")) selected #endif>Religion 1</option>
Or if you want a bit more convenience, you could add an accessor method in the user model:
public function getDecryptedReligionAttribute()
{
return empty($this->diversity->religion) ? '' : decrypt($this->diversity->religion);
}
That would allow you to simple pass $user->decrypted_religion to the old function:
<option value="Religion 1" #if(old('religion', $user->decrypted_religion) === "Religion 1") selected #endif>Religion 1</option>

In order to decrease bloat, you can put the check for the properties in the User model. I'm not going to write all the code but a stub like this in User:
public function decryptProperty($property) {}
Where you can check if property is set, decrypt it, and return the value. Then in your view you can reduce bloat by just checking the user model directly:
<option value="Religion 1" #if(old('religion', $user->decryptProperty($user->diversity->religion) === "Religion 1")) selected #endif>Religion 1</option>
This allows you to keep most of your logic in your model and keep a mostly tidy view (highly recommended).

Related

Display other table data from drop down list when edit

Is that possible to get data from other table?
Let say in create table, I get all the info from genre table and display all data in drop down list
<select name="mov_genre" id="mov_genre" class="form-control input-sm">
<option value="">类型</option>
#foreach(App\Genre::all() as $gData)
<option value="{{$gData->gen_title}}">{{$gData->gen_title}}</option>
#endforeach
</select>
In edit page, I want to display it as well but how to display it as the genre I selected when create?
In my opinion, you should use $gData->id as value of each option. Because normally you store the id as foreign key and not something like the title.
But to your question itself: You can simply add an if statement that checks within the foreach loop if the current item is the selected one. In my example I assume you have a variable $movie which is the entry you want to edit.
<select name="mov_genre" id="mov_genre" class="form-control input-sm">
<option value="">-- SELECT GENRE --</option>
#foreach(App\Genre::pluck('gen_title', 'id') as $key => $value)
<option value="{{ $key }}" {{ optional($movie)->genre_id === $key ? 'selected' : '' }}>{{ $value }}</option>
#endforeach
</select>
Please note that I swapped App\Genre::all() for App\Genre::pluck('gen_title', 'id'). This will only load the both fields gen_title and id and put them in an array where id is the key and gen_title the value. It is done for better performance as we do not load unnecessary data.
Also note that optional($movie) will return null when $movie is not set. This is done to reduce weird if statements and is common practice.

Laravel ignores select input validation if no option is selected

I have a form with some fields which I want to validate using Laravel's validate() method.
public function postSomething(Request $req) {
...
$this->validate($req, [
'text_input' => 'required',
'select_input' => 'required'
]);
...
}
The issue is that if the form is submitted without selecting an option from the select input it is ignored in the request and Laravel doesn't validate it despite the fact that it is added to the ruleset with the required validation rule. Empty text inputs are being validated correctly.
+request: ParameterBag {#42 ▼
#parameters: array:1 [▼
"text_input" => ""
"_token" => "TCDqEi2dHVQfmc9HdNf8ju1ofdUQS6MtDBpUMkl7"
]
}
As you can see, the select_input is missing from request parameters if it was left empty.
Here is the HTML code for my select input:
<select class="form-control" name="select_input">
<option disabled selected>Please select...</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
Is there a way to make the validation work for all fields from the ruleset even if some of them are not present in the request?
From Laravel 5.1 validation documentation:
required
The field under validation must be present in the input data and not empty. A field is considered "empty" is one of the following conditions are true:
The value is null.
The value is an empty string.
The value is an empty array or empty Countable object.
The value is an uploaded file with no path.
P.S. I'm using Laravel 5.1, so present method is not available.
Your html should look like this
<select class="form-control" name="select_input">
<option value="" selected >Please select...</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
$this->validate($req, [
'text_input' => 'required',
'select_input' => 'required',
]);
If your select box values are integer then
you can use required with integer like
$this->validate($req, [
'text_input' => 'required',
'select_input' => 'required|integer',
]);
Or if you have limited options for that select box then you can use
'select_input' => "required|in:val1,val2,val3",
You made it's option disabled, so it won't send anything through your form.
Change your select box to
<select class="form-control" name="select_input">
<option value="">Please select...</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
There are few options I can recommend:
Manually validate the request without using the validation extended in the Controller, I.e:
//validator FACADE
$ validator = Validator::make ($request->all(), [
// rules here
]);
By this you can monitor which fields are passed and which one are not passed.
Secondly, set a default value for the select list and check that value when you are validating in the Controller, that is, if you have this default value then nothing is selected. You definitely will have only the fields submitted in your Controller.

How to get value from select value in Laravel

i need to get the value from a select tag, but the problem is that i need to send the value to the route for example :
<select name="feeling">
<option value="0">Joyous</option>
<option value="1">Glad</option>
<option value="2">Ecstatic</option>
I neeed to send the value to a route like this:
retrieve_money/0/account
How can i get the value and send into another route
retrieve_money/{in this camp i need the value}/account
Thanks.
Try this:
You could accomplish this using JavaScript by making the following modifications
In View
<select onChange="newFunction(this)" name="feeling">
<option value="0">Joyous</option>
<option value="1">Glad</option>
<option value="2">Ecstatic</option>
In Script
function newFunction(newVal){
window.location.href = '/retrieve_money/'+newVal+'/account';
}
In Routes
Route::get('/retrieve_money/{selectVal}/account', ['uses' => 'DemoController#demoFunction');
Hope this would get you started.

Laravel/Blade Drop Down List - For more than one field

I'm trying to use blade to display a dropdown list from table data. The problem I have, is that I want to display the results of two fields in the table concatenated, not just one.
So I want something to render something like;
<select id="agreement_type" name="agreement_type">
<option value="1">Agreement Field 1 - Agreement Field 2</option>
<option value="2">Agreement Field 1 - Agreement Field 2</option>
<option value="4">Agreement Field 1 - Agreement Field 2</option>
</select>
My controller currently looks like this;
$agreements = Agreement::lists('agreement_type','id');
return View::make('client_agreements.create')
->with('agreements', $agreements);
My blade view currently looks like this;
<div class="form-group">
{{ Form::label('agreement_type', 'Agreement type') }}
{{ Form::select('agreement_type', $agreements) }}
</div>
I have tried to amend the view and controller in various ways to get the desired output. But can't get it to work.
I want to display agreement_type and level and have the id set as the value so I tried;
$agreements = Agreement::lists('agreement_type'.'level','id');
But this just displays level as the value and completely ignores id.
This is the simplest method. Just use a foreach loop to build the options array:
$agreements = Agreement::all();
$agreementOptions = array();
foreach($agreements as $agreement){
$agreementOptions[$agreement->id] = $agreement->agreement_type.' '.$agreement->level;
}
return View::make('client_agreements.create')
->with('agreements', $agreementOptions);
However you can also define an attribute accessor in your model. You can use that to create new properties that can be accessed normal, but you can run logic to generate them (like combining to attributes)
public function getSelectOptionAttribute(){
return $this->attributes['agreement_type'].' '.$this->attributes['level'];
}
And then you can use lists:
$agreements = Agreement::all()->lists('select_option', 'id');
(Laravel converts SelectOption (studly case) from the method name to select_option (snake case) for the attribute, so don't get confused by that)

Pre-selecting values in a multi-select drop-down list in laravel

I'm relatively new to Laravel (and using Laravel 4), but been around PHP and C# a long time. Seems like this should be easy, but I can't find anywhere that tells me how to do this.
In my Controller I get the data from the database and send it to the view like this:
$sections = DB::table('paperSections')->lists('section','id');
return View::make('layouts.publisher.step2', array('sections' => $sections));
in my View, I have the following:
{{ Form::select('sections[]', $sections, '', array('multiple')) }}
which generates a select list like this:
<select multiple="multiple" id="sections" name="sections">
<option value="1">News</option>
<option value="2">Sports</option>
<option value="3">Features</option>
<option value="4">Arts and Entertainment</option>
<option value="5">Technology and Science</option>
<option value="6">Op-Ed</option>
</select>
Lets assume I have a string (e.g. "1,3,5") which represents the multiple options selected previously. How can I re-select those three options using that string?
Pass array of selected options as 3rd param:
$selected = explode(',', $idsAsString);
Form::select('sections[]', $sections, $selected, ['multiple'])

Categories