What is the best practice to show old value when editing a form in Laravel? [closed] - laravel

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
I am writing the logic for an edit form and have some complications when displaying data in the inputs.
When I initially show the form, I show the records values like:
value="{{$dog->title}}"
Then when the form does not pass the validation I need to show the old input, so that user does not loose what he has already input. So I need to have a way to display old data like:
value="{{old('title')}}"
Because I need to input old data in case it exists, I ended up with this code:
value="{{$dog->title or old('title')}}"
And in controller I check if Request has old input, I assign the $dog var a null value.
I wanted to ask if that is considered an OK practice or is there a better and 'correct' way to do it?

Function old have default parameter if no old data found in session.
function old($key = null, $default = null)
You can replace expression in template with
value="{{old('title', $dog->title)}}"

I know this has already been answered but I thought I would leave a little snippet here for others in the future.
Setting old value on input as #ikurcubic posted can be used the same way on radio button or select:
<input type="text" name="name" value="{{ old('name', $DB->default-value) }}" />
Select option:
<option value="Jeff" {{ old('name', $DB->default-value) == 'Jeff' ? 'selected' : '' }}>Jeff</option>
Radio Button:
<input type="radio" name="gender" value="M" {{ old('name', $DB->default-value)== "M" ? 'checked' : '' }} />
Another way of doing it; write a small if statement to determine which value should be evaluated:
#php
if(old('name') !== null){
$option = old('name');
}
else{ $option = $database->value; }
#endphp
<select name="name">
<option value="Bob" {{ $option == 'Bob' ? 'selected' : '' }}>Bob</option>
<option value="Jeff" {{ $option == 'Jeff' ? 'selected' : '' }}>Jeff</option>
</select>
<input type="radio" name="gender" value="M" {{ $option == "M" ? 'checked' : '' }} />
<input type="radio" name="gender" value="F" {{ $option == "F" ? 'checked' : '' }} />
Setting old value of input with an array name e.g name="name[]":
<input type="text" name="name[]" value="{{ old('name.0) }}" />
This will give you the old value of the input with an index of 0.
I have tested this and it works.

Another way to do that is get the data from the dog class, like this:
value="{{old('title') ?? $dog->title }}"
Why? Because old() is for validation; when you fail validation, the input will remain available in the field. In the case where validation hasn't fired yet, value will be filled with $dog->title.

I solved that issue in my application
if you want to get old previous inserted value in input you should try this one
I did like this.
function SaveData(Request $request)
{
$sValidationRules = [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'phone' => 'required',
];
$validator = Validator::make($request->all(), $sValidationRules);
if ($validator->fails()) // on validator found any error
{
// pass validator object in withErrors method & also withInput it should be null by default
return redirect('Your Route Hare')->withErrors($validator)->withInput();
}
Employee::create($request->all());
return redirect(' your route hare ');
}
& after then get old data in input field value like this using {{ Request::old('firstname') }}
Happy Coding. :)
<input type="text" name="firstname" id="firstname" value="{{ Request::old('firstname') }}" class="form-control" placeholder="First Name">

Old Data: input type text | phone | number | ...
<input type="text" name="my_text" value="{{old('my_text')}}">
Old Data: input type checkbox | radio
<input type="checkbox" {{ old('my_checkbox') == 'on' ? 'checked' : '' }} name="my_checkbox">

There is nothing wrong with the way you are doing things as Laravel gives multiple ways to handle the situation you're describing.
What I would suggest is using the Laravel Collective Form and HTML packages to build your form. This package will automatically handle binding old request values to your form if validation fails
https://laravelcollective.com/docs/5.2/html

Related

Laravel - Is there any better approach to check the checkbox with the user previous input value in blade?

I have a checkbox
<input type="checkbox" name="example">
The user submits the form and return back due to failed validation so I want to show the previous state of the checkbox
<input
type="checkbox"
name="example"
{!! old('example') ? 'value="1" checked' : 'value="0"' !!}>
First question here is that, what to do with validation now? if it was 0 or 1 I would add boolean validation but now the first time it is on and after that it is 0 or 1.
Someone may say if you use that {!! old('example') ? 'value="1" checked' : 'value="0"' !!} initially, its value won't be on anymore.
So my first question changes to this: Initially the value of old('example') is null so the checkbox doesn't have checked attribute and the value of checkbox would be 0. Now when the user submits the form the old('example') has value (IT IS NOT NULL) and so this time the the checkbox has checked attribute and its value is 1 while it mustn't.
========
Another issue I encounter with is that, if old('example') has true value (which means the user had checked the checkbox), I should put something to check the checkbox. But it is not finished yet. I want to check the value of example that is in database so if the old('example') has false value(which means the user hadn't checked the checkbox) I want to check the value of example, if its value is 1 to check the checkbox and set the value of checkbox to 1 else 0. So what comes to my mind is this:
<input
type="checkbox"
name="example"
value="{!! old('example', isset($collection) ? $collection->example : null) == '1' : '1' : '0' !!}">
Now the problem is that old('example') would be on or NOTHING. And the value of $collection->example would be 1 or 0 or null. So if I compare it with '1' it won't be true even if the old('example') is true and similarly if I compare it with on, it won't be true even if the value of $collection->example is true. So let's do this:
#if(old('example') == 'on' || (isset($collection) && $collection->example))
<input type="checkbox" name="example" value="on" checked="checked">
#else
<input type="checkbox" name="example">
#endif
by this code above the issue is fixed. But is there any other better approach?
So my question is what to do with the validation in the back-end and of course what to do with check-boxes in front-end in an better approach without getting involved in jQuery and such a like?
I think it will solve your problem give it a try.
Blade file:
<input type="checkbox" name="example" value="{{ old('example') ?? '1' }}"
{{ old('example') == '1' ? 'checked' : null }} required>
The required will force the user to check the checkbox on the frontend, and on the backend, you can use the required validation because we can't trust the frontend validation.
Controller:
public function store(Request $request)
{
$request->validate([
'example' => 'required',
]);
}

Laravel can't uncheck checkbox using old with default value set

I have a very simple checkbox in my application form
<input type="checkbox" name="active" {{ ( empty(old('active')) ? '' : ' checked' ) }}>
My requirements are:
the checkbox should be checked by default when the user arrives on the site for the first time
the checkbox should keep its value after the form validation fails
To me, it seems impossible to achieve this simply by using old as it will either
(2) remember the value after validation fails but it will not be checked by default at the beginning
(1) be checked by default, e.g. old('active', true) but then it will not be possible to uncheck it (i.e. unchecked box will be checked after validation fails because the default value is set in old).
What is the standard way of dealing with this? Or is there no way around using another field to check if the form was submitted?
<input type="checkbox" name="active" {{ ( empty(old('active')) && !empty(old('submit')) ? '' : ' checked' ) }}>
<input type="hidden" name="submit" value="submit">
Thank you
This maybe dirty but you can append empty string if the $request->active is null.
The code is something like this $request->active ?? '';.
You can pass the default value into old helper.
Try this:
<input type="checkbox" name="active" {{ old('active', true) ? 'checked' : '' }}>

Laravel 5: Check for Specific Error

I have Password and Confirm Password inputs. I have coded these inputs so that in the event of an error the inputs highlight, like so:
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}>
<label>Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group {{ $errors->has('password_confirmation') ? 'has-error' : '' }}>
<label>Password</label>
<input type="password" name="password_confirmation" class="form-control">
</div>
In my Controller, I validate these inputs as follows:
$this->validate($request, [
....
'password' => 'required|min:8|confirmed',
'password_confirmation' => 'required',
....
]);
When either input is null and/or less than 8 characters, the inputs highlight as expected. However, when the inputs don't match, I would logically expect the Confirm Password input to highlight. However, it is the Password field that highlights, because that is the input that the "confirmed" rule is set to.
The "$errors->has()" method simply checks if an error exists for an input. Is there a way to check if an input has a specific kind of error?
Yes, you can get the array of errors for a given input name by using:
{{ $errors->get('password') }}
So you can check if the password errors array has the confirmation error and then add the additional class to your confirmation input field:
#if (in_array(trans('validation.confirmed', ['attribute' => 'password']), $errors->get('password'))) has-error #endif
And the helper methods may vary between Laravel versions:
Laravel < 5.4: trans('validation.confirmed', ['attribute' => 'password'])
Laravel 5.4: __('validation.confirmed', ['attribute' => 'password'])

How do I bind a radio button value to my model? Laravel 5.3

I have a form with a couple of radio buttons;
<div class="form-group{{ $errors->has('procurement') ? ' has-error' : '' }} col-md-6">
<label for="procurement" class="col-md-6 control-label">Procurement Type <span class="red">*</span></label><br>
<div class="col-md-12">
<input id="procurement" type="radio" name="procurement" value="owned"> Owned
<input id="procurement" type="radio" name="procurement" value="rental"> Rental
#if ($errors->has('procurement'))
<span class="help-block">
<strong>{{ $errors->first('procurement') }}</strong>
</span>
#endif
</div>
I am reusing the form for editing purposes so I want to be able to bind the object's value for 'procurement' when I present the form in edit view. I am able to use this bind the values for text inputs;
value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"
But this does not work for radios or selects. What should I be doing? I am NOT using the Form facade for this.
Thanks!
You can use selected and checked for what you want to do. Just add it to the end of the element, and it will select/check the element.
Something like this for input type radio:
<input id="procurement" type="radio" name="procurement" value="owned" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'checked' : '') }}> Owned
<input id="procurement" type="radio" name="procurement" value="rental" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'rental' ? 'checked' : '') }}> Rental
And this for select options:
<option value="something" {{ old('model') === "something" ? 'selected' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'selected: '')}}>Something</option>
Side note: I'd recommend making sure that old('something') comes before other possible values when you're filling values in. For instance, you had:
value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"
which would override the user's original input with database results (if any, of course) upon a failed submission. So if I was say, updating my name in a text field, and there were errors to the form, it would direct me back to the form and lose my input because the database results are before the old value. Hope that makes sense!

How to validate, that there is at least one checkbox checked?

I have a form for creating a question with multiple(as many as one wishes) possible answers. Here is the picture:
The code for a single possible answer:
<div class="input-group">
{{-- Checkbox for the answer --}}
<span class="input-group-addon">
<input type="checkbox" name="answer[0][is_correct]" value="1">
</span>
{{-- Input field for the answer --}}
<input type="text" class="form-control" name="answer[0][body]">
{{-- . . . --}}
</div>
I need to validate that, there exist at least three answers for a question and at least one of them is correct. How can I achieve this?
I would consider separating your answer text fields from your answer checkboxes for the sake of clarity.
Below hasn't been tested - but something like the following should hopefully help you along?
$numAnswers = count($input->only('answers_text'));
$rules = [
'answers_checked' => 'array|min:1|max:' . $numAnswers,
'answers_text' => 'array|min:3|required',
'answers_text.*' => 'required|string',
];
$v = Validator::make($input, $rules);
if ($v->fails()) {
return response()->json($v->errors(), 422);
}
...

Resources