How to get checkbox value in a Laravel controller? - laravel

I have a checkbox in my form and I want to save its value into the database. When I check it, its value will be 1 and when I uncheck it then it's value will be 0. However, in the controller, I am getting NULL all the time. But why? Is it possible to solve without jQuery?
Blade/View
<form action="{{ route('admin.categories.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group>
<label>
<input type="checkbox" name="category_is_menu"
value="{{ old('category_is_menu', isset($category) ? 'checked' : '') }}"/>
</label>
</div>
<input class="btn btn-success" type="submit" value="Submit">
</form>
Controller
public function store(Request $request)
{
$category = new Category();
$category->category_is_menu = $request->category_is_menu;
return $category;
}
Unfortunately, it's giving me NULL for category_is_menu.

Add a hidden input with the negative value just before the checkbox input (with the same value in the name attribute)
<div class="form-group">
<input type="hidden" name="category_is_menu" value="0"/>
<input type="checkbox" name="category_is_menu" value="1" {{ old('category_is_menu', isset($category) ? 'checked' : '') }}/>
</div>
The value in the checkbox input needs to be always 1.
A checkbox input in not sent in the request when it's unchecked, in that case the hidden input will be sent with the value 0.
When the Checkox is checked, it will overwrite the value to 1.

Either use the hidden input trick as mentioned in the other answers or just check if the input was passed at all. If it was passed at all it was checked, if its not there it was not checked:
$category->category_is_menu = $request->has('category_is_menu');
If it was checked you get true, 1, if it wasn't checked you get false, 0.

Related

Laravel, can't set old value to bootstrap datetimepicker, when validate

I'm using Laravel 8.5 (current version)
Therefore I'm new to laravel, I'm trying to learn with simple examples.
I have some blade view, with code part bellow:
<div class="form-group">
<input type="hidden" id="hdnLocale" value="ru">
<input type="hidden" name="hdndefDate" id="hdndefDate" value="2021-01-17">
#if (old('hdndefDate'))
<input type="hidden" name="hdndefDate" value="{{ old('hdndefDate') }}">
#endif
<label for="picker">Birthday</label>
<div class="input-group">
<div class="input-group-prepend">
<button type="button" class="input-group-text" id="toggle">
<i class="fa fa-calendar-alt"></i>
</button>
</div>
<input type="text" id="picker" name="picker" value="{{old('picker')}}" class="form-control" readonly>
</div>
</div>
As you see I'm using two hidden inputs, with a variable value from the controller, that must be set from javaScript (In a simple I use exact value).
Here is my script:
<script>
var locale = $('#hdnLocale').val()
jQuery.datetimepicker.setLocale(locale)
jQuery.datetimepicker.setDateFormatter('moment')
var yourDate = $('#hdndefDate').val();
$('#picker').val(yourDate);
$('#picker').datetimepicker({
timepicker: false,
datepicker: true,
format: 'YYYY-MM-DD',
defaultDate: yourDate,
weeks: false,
hours12: false,
step: 15,
yearStart: 2015,
yearEnd: 2022,
dayOfWeekStart: 1
});
$('#toggle').on('click', function () {
$('#picker').datetimepicker('toggle');
})
</script>
I have some other inputs also, that I've validating via the controller,
when I change the value of datepicker, post form and validation fails, other fields set with old values, except datepicker.
Where I have messed something? I wanna set the old value to datepicker, when validation fails.
As I discovered later, the old value is set and immediately refreshed with default value '2021-01-17'
Seems like you're getting two inputs with name hdndefDate when old values from this input exists.
And in your JS you're getting the value from the input #hdndefDate, that holds the default value.
Change your #if to something like this:
#if (old('hdndefDate'))
<input type="hidden" name="hdndefDate" id="hdndefDate" value="{{ old('hdndefDate') }}">
#else
<input type="hidden" name="hdndefDate" id="hdndefDate" value="2021-01-17">
#endif
Or even better:
<input type="hidden" name="hdndefDate" id="hdndefDate" value="{{ old('hdndefDate') ?? 2021-01-17}}">

Laravel - Redirect users back to another form with all data intact, on clicking Previous button

I have two forms as below
Form 1
<form id="form1" action="loc1" method="post">
<div class="form-group">
<label for="exampleDOB">Date of Brth:</label>
<input type="text" class="form-control" id="dob" name="dob" placeholder="Date of Birth"
value="{{$tuser->DOB ?? ''}}" >
<div class="error text-danger"></div>
</div>
<button type="submit">Next Step</button><br><br>
<button type="button">Previous </button>
</form>
Form 2
<form id="form2" action="loc2" method="post">
<div class="form-group">
<label for="exampleMob">Mobile Number:</label>
<input type="text" class="form-control" id="mobno" name="mobno" placeholder="Valid Mobile
Number" value="{{$tuser->mobno ?? ''}}" >
<div class="error text-danger"></div>
</div>
<button type="submit">Final Step</button><br><br>
<button type="button">Previous </button>
</form>
$tuser is an object containing all the data for that user, from the database
When users click on Next Step in Form 1, the data is stored in database and the user is directed to Form 2.
But the problem is- on clicking the Previous button, I am losing all the pre-filled data in the Previous form. How can I retain form data (to be shown in the input fields as available in the database)?
if you have saved them in DB, so you can retrieve all of it using an id and store it in session like:
session->put("form_1_id",$DBInsertedId);
in form 1 you can check if there are any results, you can retrieve it like:
if(session->has("form_1_id"))
return view('form_1',['filled_data' => Model::find(session->get("form_1_id")) ]);
and in the view you can check for parameter existence form_1_id like you did:
<input type="text" class="form-control" id="dob" name="dob" placeholder="Date of Birth"
value="{{$filled_data->DOB ?? ''}}" >
just add a filled name id in your input view and fill it if form has been filled out before. since doing this can assure you that the filled form will be updated if there was a record for it before:
<input type="hidden" id="id" name="id" value="{{$filled_data->id ?? ''}}" >
and in your controller:
Model::insertOrUpdate(['id' => $request->id ], ... );
UPDATE:
insertOrUpdate Equivalent in psudo-code :
if(DB::exist(['id' => $request->id]))
update(['id' => $request->id , ... ]);
else
insert([ ... ]);

laravel 7 - unable to pass input parameter to form action for searching purpose

how i can pass input value form action and replace number 5? the below works if i put numbers only, then it pass it to route then controller:
<!--Search to mysql -->
<form action="{{ route('propertyname.show', 5)}}" method="GET" role="search">
#csrf
<Label for="id">search:</Lebal>
<input type="text" id='id' name="id" placeholder="Search plzz">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
<input type="submit" name="submit" value="Serach">
</form>
Route::get('/property_name/{id}','RsmsController#show')->name('propertyname.show');
the above works if I typed number 5 manually which I don't want, I want it to read\input from FORM TEXT and fired when clicking on the form button to send the value to the controller.
http://127.0.0.1:8000/property_name/5
enter image description here
You can take a look at simple jQuery on click/submit method.
$(function() {
$("#myform").submit(function(e) {
var actionUrl = "{{ url('/property_name/') }}" + $("#id").val();
$(this).attr("action", actionUrl);
});
});

can't get old() to work in laravel

in my blade i have 2 radio inputs
<form class="" action="{{route('admin.album.search')}}" method="post">
<input id="slug" type="radio" name="search" value="slug" >
<input id="id" type="radio" name="search" value="id">
in the same blade file I test to see old value of radio input
{{ old('search')}}
When I select first radio button and submit the form and page reloads I expect that old will be selected radio button value but nothing comes out. What could I be doing wrong?
Try this:
<form class="" action="{{route('admin.album.search')}}" method="post">
{{ csrf_field() }}
<input id="slug"
type="radio"
name="search"
value="slug"
{{ (old('search') == 'slug') ? 'checked': '' }}>
<input id="id"
type="radio"
name="search"
value="id"
{{ (old('search') == 'id') ? 'checked': '' }}>
N.T. If you submit post form request you must be specify csrf_field(). Otherwise it gives you token mismatch exception.

Laravel: textarea does not refill when using Input::old

I am experiencing that only the Input Textfields respond as expected when I write the code to repopulate a form (when errors were found for example) or when from a table row I click in the Edit button and I go to an editable form. The field for a textarea is not repopulated so it comes up empty, therefore, if I save it, I would delete the content of the textarea. (I know I am asking a succession of questions lately, the reason is that I have basically finished my application and I left for the end the minor things I could not solve, so my apologies for that).
here is an example of what I am saying:
This WORKS for input textfield:
WORKS
<div class="col-md-4">
<label for="relato">Charges</label>
<input type="text" name="expenses" maxlength ="30" class="form-control"
value = "{{ $user->expenses }}"/>
</div>
That is, the $user->expenses fills the textfield of the form that comes up when clicking the Edit button of a table row.
However, that does not work for a textarea field:
<div class="row">
<label for="relato">Description</label>
<textarea name ="message" id="message" rows="5" cols="100" value = "{{ $user->message }} class="form-control"
</textarea>
</div>
See? that part $user->message will not pass the content to the textarea of a form.
Similarly: with Input::old
Works for an Input textfield
WORKS
Email: <input type="text" class="form-control" name="email" {{ (Input::old('email')) ?' value ="' . e(Input::old('email')). '"' : '' }}>
DOES NOT WORK FOR TEXTAREA
<div class="form-group">
<label for="relato">Une petite description</label>
<textarea id="message" name = "content" rows="10" cols="50" onKeyPress class="form-control" {{ (Input::old('content')) ?' value ="' . e(Input::old('content')). '"' : '' }}
">
</textarea>{{ $errors->first('content')}}
</div>
And the controller is also trying to refill the form by sending ->withInput
if($validator->fails()){
return Redirect::route('usersgetformtopostads')
->withErrors($validator)
->withInput();
}
but, as I said, it only works for textfields. Does not repopulate me a select list or a textrarea
By the way, I have looked a related question here where the author says he could not repopulate a File field and he was told that "you cant" and he gave that as a correct answer, however, I have been able to repopulate Files uploaded, not having any problem with that.
textarea does not have a value attribute. Values in textarea should be inside <textarea></textarea>, so in your case:
<textarea id="message" name = "content" rows="10" cols="50" onKeyPress class="form-control">
{{{ Input::old('content') }}}
</textarea>
Just figured it out, put the old value in between the brackets as below
<textarea name="message">{{ old('message') }}</textarea>
This is another way to do the same but with the Forms component from laravel:
{{ Form::textarea('content',Input::old('content'),array('id' => 'message')) }}
I'd like to add one thing, if you use Form Class for the form and elements then you don't need to explicitly right the Input::old('element-name') to retrieve the value of the previous form submission.
Just use
{{ Form::text('name', null, array('id'=>'name', 'class' => 'class-to-apply')) }}
And you're good to go.
Here, null value for the text field will be null for the first time, and if you redirect back this page with input then this will automatically grab the value.
Sorry for late reply
{{Form::textarea('mobile_message', isset($notifications -> mobile_message) ? $notifications -> mobile_message : null, 'id'=> 'mob_id','class' => 'form-control'))}}
<div class="control-group hidden-phone">
<label class="control-label" for="textarea2">Category Description</label>
<div class="controls">
<textarea style="resize:none" name="category_description" required rows="6">
<div class="control-group hidden-phone">
<label class="control-label" for="textarea2">Category Description</label>
<div class="controls">
<textarea style="resize:none" name="category_description" required rows="6" >{{$category_info->category_description}}</textarea>
</div>
</div>
</textarea>
</div>
Normally, textarea does not have a value attribute, but there's a way you can add that with the current Laravel version (which is 8+)
<textarea>{{{ Request::old('content') }}}</textarea>

Resources