Form input not validate if input is disabled - php

I have a selection that is disabled is the page not editable is.
Here is my code:
<select name="status" class="form-control" id="status" #if($page->editable == 0) disabled #endif>
<option value="1" #if ($page->status == 1) selected #endif>Online</option>
<option value="0" #if ($page->status == 0) selected #endif>Concept</option>
</select>
But as the input is disabled he send no values with.
And now comes the problem.
I validate the form. Here is my code of validate the form:
$form = $request->validate([
'status' => 'required',
]);
But I get the error now that the value status is empty and required.
Do you now how to set the validation that he only is required is the form is not disabled?
I hope that you can help me.

Firstly, You should use separate function for store and update,
For store, Your validation code seems right, but you can add boolean rule
$form = $request->validate([
'status' => 'required|boolean',
]);
For update, you can use validation rule like this,
$form = $request->validate([
'status' => 'nullable|boolean',
]);
If you are using same function for store and update, you should send value for editable status and you can apply validation rules according editable status like this,
if ($request->editable) {
....
}
else {
...
}
I hope this will help

Related

how to add a new input as a dropdown type and with filled default options to laravel jetstream registration form

my need is to add a new input as a dropdown type and with filled default options to laravel.8 jetstream registration form.
my problems are:
how to add dropdown input to the registration blade file? use jetstream component or have to create a new component based on livewire or pure laravel component?
where default options for dropdown must be prepare and sent to the blade file?
how can I get selected options from users in app/Actions/Fortify/CreateNewUser.php?
thanks
I understand this is not a full answer to all of your questions but should help.
You can just add a standard select, something like this:
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You can get/use that value in app/Actions/Fortify/CreateNewUser.php accessing the array. The following inserts the new value into the database:
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'car' => $input['cars']),
'password' => Hash::make($input['password']),
'api_token' => Str::random(60),
]);
You will also need to update the app/Models/User.php Model and add the new value as fillable (and of course have added the field to your User Model via a migration):
protected $fillable = [
'name',
'email',
'password',
'car',
];

Laravel 5.8 on validation error return to specific view with all input -> old not working

TLDR;
(In Laravel 5.8) Upon validation error, how can I return to a specific view with all input and the errors?
I'm creating a multistep form in which I need to validate the input on each step. Therefore, I have created the first page as a create and then the subsequent pages to update.
On the second page, when the validator fails, I am returning the specific view as I want it to go to this partial and not the beginning of the form. I am also returning the errors and the input on fail.
Controller:
if ($validator->fails()) {
return view('partials.question_02_' . $type)
->with('type', $type)
->with('id', $id)
->withErrors($validator)
->withInput($request->all());
}
Here is my validation logic:
$validator = Validator::make($request->all(), [
'email' => 'required',
'first_name' => 'required',
'last_name' => 'required',
'phone' => 'required',
]);
With this, I am able to go back to the specific view and with the validation errors. However, I am not able to receive the old input.
The following in Blade will show that there is an erro (the error class appears), however, it will not show the old input.
<input class="#if ($errors->has('first_name')) error #endif"
type="text" name="first_name" placeholder="First Name" value="{{ old('first_name') }}">
*note, I only put it on two lines for legibility here
What is weird is that if I die and dump the request, I can see all of the input:
dd($request->all());
However, if I try to get it from the session, I don't see any of the input:
#if($errors)
{{var_dump(Session::all())}}
#endif
Any idea why {{ old('first_name') }} isn't working in this case?
Thanks!
You're Returning a view return view() instead you need to return redirect return redirect()as a return view will generate a fresh page and old() will not work.
So instead of
return view('partials.question_02_' . $type)
Use
return redirect()
&in your case
redirect()->action('LoginController#secondPage'); //you controller and method handling your second page

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.

Laravel Validation with checkbox

If use_shipping is un-checked and user did not enter the value in the shipping_note - validation should have passed but it has failed?
<input type="hidden" name="use_shipping" value="0">
<input type="checkbox" name="use_shipping" value="1" {{ old('use_shipping', $delivery->use_shipping) ? 'checked="checked"' : '' }}>
Text
<input type="text" name="shipping_note" value="">
In Laravel request class:
public function rules()
{
return [
'use_shipping' => 'boolean',
'shipping_note' => 'required_with:use_shipping',
];
}
The required_with validation states:
The field under validation must be present and not empty only if any of the other specified fields are present.
Because of your hidden input, the shipping_note field will always be present. Since the field is present even when the checkbox is unchecked, the required_with validation will always be triggered.
Most likely what you're looking for is the required_if validation, which states:
required_if:anotherfield,value,...
The field under validation must be present and not empty if the anotherfield field is equal to any value.
public function rules()
{
return [
'use_shipping' => 'boolean',
'shipping_note' => 'required_if:use_shipping,1',
];
}
This should cause shipping_note to only be required when the value of use_shipping is 1, which should only happen when the checkbox is checked.

Post parameters through a form, to create a URL based on said parameters

Within a form, a user can search and select within 2 drop downs (city and town, for example). Once they submit the form, I want that to redirect to a URL with the chosen dropdown options in the URL.
So, upon form submission, they will be redirected to www.domain.co.uk/city/town.
I'm struggling to get to grips with the concept of URL parameters, and how to pass them to the route!
Current set up:
{!! Form::open(['route' => ['search'], 'method' => 'POST', 'id' => 'search']) !!}
The two fields of which I want to post to the URL are:
<input type="hidden" name="town" id="town">
and
{!! Form::select('city', $city, null,
['class' => 'form-control', 'id' => 'city', 'required'])
!!}
I'm aware I'll have to post the ID of the latter, and so I'll have to look up the actual name field within the DB and return it to use (I have to generate the slug anyways).
Route:
Route::post('{city}/{town}', ['uses' => 'Controller#search',
'city' => Input::get('city'), 'town' => Input::get('town')]
)->name('search');
Controller:
public function search(Request $request)
{
return view('location.search');
}
How can I use the two fields' values within the URL when they're redirected? I think I'm approaching it the wrong way but I can't think of alternatives.
Any help would be massively appreciated! Thank you in advance.
You could change your route structure to something like:
Route::post('search', 'Controller#search')->name('search');
Route::get('{city}/{town}', 'Controller#show')->name('location.show');
And in your controller:
public function show(Request $request, $city, $town) {
// Do something with $city & $town
return view('location.show');
}
public function search(Request $request) {
$input = $request->only('city', 'town');
// TODO: validate the input
return redirect()->route('location.show', $input);
}
How about we take another approach and use javascript without the form. An example as follows:
<input type="hidden" name="town" id="town" value="town">
<select name="city" id="city">
<option value=""></option>
<option value="City1">City 1</option>
<option value="City2">City 2</option>
<option value="City3">City 3</option>
<option value="City4">City 4</option>
</select>
<button type="button" onclick="redirect()">Redirect</button>
<script>
function redirect(){
var city = document.querySelector('#city').value;
var town = document.querySelector('#town').value;
if(city != '' && town != ''){
window.location = 'http://mydomain.co.ke/'+city+'/'+town;
//or
window.location = '/'+city+'/'+town;
}
else{
alert('Select a city');
}
}
</script>
As a note the input/select elements can still be created using the Form Facade
If you want your data to be available in url, your Route should be for a get request. Not a post.
Route::get('{city}/{town}', 'Controller#search');
Then, in your controller you can get them simply by adding them in your parameters list:
public function search($city, $town)

Categories