EDIT:
Your solutions are working for text inputs and textareas, but checkboxes are not working correctly for me.
This was my original checkbox:
{{ Form::checkbox('active', true, (isset($user->active)) ? old($user->active) : true, ['class' => 'custom-control-input', 'id' => 'active']) }}
I've tried a lot of possible solutions like adding old('active', isset($user) ? $user->active: true) instead, but when an error occurs I lose the values from this input. On the controller I was checking this, but if I change the input to the 'new solution' active is always false on my db:
if(!array_key_exists('active', $validated)){
$validated = array_add($validated, 'active', '0');
}
ORIGINAL QUESTION (PARTIALLY RESOLVED):
I have one blade view call edit with two forms, but each one is calling his own method/route. One form is for edit/store the user and the other is a form in a modal to change the user password. When I change the password and no validation error happens, the other form still has all of his values that is getting from old() or $user variable via index method. But if for example the passwords do not match, a validation error occurs, and the values from the edit/store user form disappear.
Forms are pretty simple (remember, they are on the same view, and the one that is giving me problems is the edit/create one), and each one call a different method from UserController
Form 1 for edit users (simplified)
#if($user->exists)
{{ Form::model($user, ['route' => ['users.update', $user], 'class' => 'needs-validation', 'novalidate'=>'']) }}
#method('PATCH')
#else
{{ Form::model($user, ['route' => ['users.store'], 'class' => 'needs-validation', 'novalidate'=>'']) }}
#method('POST')
#endif
#csrf
<div class="form-group">
<div class="row">
<div class="col-sm-4">
{{ Form::label('cif', __('users.cif'), ['class' => 'form-label']) }}
{{ Form::text('cif', (isset($user->cif)) ? old($user->cif) : '', ['class' => 'form-control', 'required','maxlength'=>'12', 'minlength'=>'9']) }}
{{ Form::hidden('validate','', ['class' => 'form-control', 'required', 'id'=>'validate']) }}
</div>
<div class="col-sm-6">
{{ Form::label('name', __('users.name'), ['class' => 'form-label']) }}
{{ Form::text('name', (isset($user->name)) ? old($user->name) : '', ['class' => 'form-control','required','maxlength'=>'255']) }}
</div>
<div class="col-sm-2">
{{ Form::label('initials', __('users.initials'), ['class' => 'form-label']) }}
{{ Form::text('initials', (isset($user->initials)) ? old($user->initials) : '', ['class' => 'form-control', 'required','maxlength'=>'5']) }}
</div>
</div>
<div class="col-sm-6">
{{ Form::label('province', __('users.province'), ['class' => 'form-label']) }}
{{ Form::text('province', (isset($user->city)) ? $user->city->province->name : '', ['class' => 'form-control', 'disabled'=>'']) }}
</div>
{!! Form::close() !!}
Form 2: Update password
<form id="change-password" action="{{route('users.change.password', $user)}}" method="POST">
#csrf
<div class="modal-body">
<div class="card-body">
<div class="panel-tag">
<p>Las contraseñas debe de coincidir y tener más de 8 carácteres</p>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Contraseña</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password" minlength="8">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirmation" class="col-md-4 col-form-label text-md-right">Confirmar contraseña</label>
<div class="col-md-6">
<input id="password-confirmation" type="password" class="form-control #error('password') is-invalid #enderror" name="password_confirmation" required autocomplete="new-password" minlength="8">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="change" type="submit" form="change-password" class="btn btn-primary">Confirmar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
</div>
</form>
UserController I'm going to paste two methods, one for store/user, the other for change the password. Update method is very similar.
public function store(StoreUserRequest $request)
{
if( $request['validate'] == 1 ){
$validated = $request->validated();
$validated['password'] = Hash::make($validated['password']);
$id = DB::table('users')->insertGetId($validated);
return redirect()->route('users.edit',['user'=>$id])->with('status', 'created');
} else {
return redirect()->back()->withInput()->with('status', 'error_dni');
}
}
public function changePassword(PasswordUserRequest $request, User $user)
{ // HERE IS WHERE I THINK IS THE PROBLEM, IF VALIDATION FAILS (FOR EXAMPLE PASSWORD CONFIRM) VALUES FROM THE OTHER FORM DISAPPEAR AND IT DOESNT GET INTO THIS METHOD
$pass = Hash::make($request->password);
$user->password = $pass;
$action = $user->save();
if ($action) {
return redirect()->back()->with('status', 'change_password_ok');
}
return redirect()->back()->with('status', 'error_change_password');
}
PasswordUserRequest This is the request to validate the password form
public function rules()
{
return [
'password' => 'required|string|confirmed';
];
}
The route would be something like:
users/{user}/edit
I've spent all day trying to fix this and still didn't found a solution. My english is not very good so please tell me if I'm not explaining something correctly and I will edit the question.
Thanks and hope that I can find a solution.
old values are from input name
<input type="text" name="input" value="{{old('input')}}"
example
<div class="col-sm-4">
{{ Form::label('cif', __('users.cif'), ['class' => 'form-label']) }}
{{ Form::text('cif', old('cif', $user->cif ?? ''), ['class' => 'form-control', 'required','maxlength'=>'12', 'minlength'=>'9']) }}
{{ Form::hidden('validate','', ['class' => 'form-control', 'required', 'id'=>'validate']) }}
</div>
//$user->cif ?? '' <- left or right hand-side operand, return right-hand if left is null or undefined
//old('input', $user->cif ?? '') <- if old input available, use old input, if not, $user will be displayed
form::checkbox:
First argument : name
Second argument : value
Third argument : checked or not checked (true or false)
Fourth argument : additional attributes
note that value is attribute(value) and checked is attribute(checked)
then
{{ Form::checkbox('active', true, (isset($user->active)) ? $user->active : true, ['class' => 'custom-control-input', 'id' => 'active']) }}
//2nd parameter (true) will always set checkbox value to 1(true)
//(isset($user->active)) ? $user->active : true <- will set default to true (checked) if $user is null or undefined
//maybe try
{{ Form::checkbox('active', $user->active ?? false, $user->active ?? false) }}
//if $user != null, put $user->active else put false
//if $user != null, set checked value based on $user->active else put false
in html looks like this
<input type="checkbox" value="1" checked="checked">
then you need to add inline event onchange="$(this).is(':checked') ? $(this).val(1) : $(this).val(0);" in the 4th parameter of form::checkbox to change the default on runtime
If I understood all correctly, you should do this way:
old('name', isset($user) ? $user->name : ''),
Here you trying to get old name input, and if it doesn't exist, in second parameter od old function you are getting default value, which is user's name in case of user exists
There is documentation, which can help you to understand much more.
I am trying to store my checkbox values in database. I have these three tables.
fields
id name
1 gender
2 looking_for
field_values (here field_id references id on fields table)
id field_id value label
1 1 1 Men
2 1 2 Women
3 2 3 Relationship
4 2 4 Friendship
5 2 5 Marriage
user_interests (here field_id references field_id on field_values table and value_id references value on field_values table)
user_id field_id value_id
1 1 2
1 2 4
1 2 5
gender in blade uses option values and looking_for uses checkbox values. I made one function that is trying to update both of them. I use two foreaches in my function and I am able to successfully update gender option, but I am unable to update looking_for option. When I click submit button nothing happens, also when I dump anything inside that foreach that is supposed to update checkboxes it doesn't dump. Any help is greatly appreciated. Here is my code.
web.php
Route::patch('profile/interests', 'UserProfileController#updateInterestsData')->name('profile.update.interests.data');
UserProfileController.php
public function updateInterestsData(UpdateInterestsDataRequest $request)
{
$user = User::with('userProfile')->where('id', Auth::user()->id)->firstOrFail();
$request->validated();
$userId = $request->input('user_id') ? $request->input('user_id') : Auth::user()->id;
$data = $request->all();
$options = [
'gender' => 1,
'looking_for' => 2
];
foreach ($options as $fieldName => $fieldId) {
if (! empty($data[$fieldName])) {
DB::table('user_interests')
->where('user_id', $userId)
->where('field_id', $fieldId)
->delete();
if (is_array($data[$fieldName])) { // CHECKBOX FIELDS AND HERE IT DOESN'T WORK!!!
//dd('DIE!!!!!!') IT DOESN'T ENTER HERE!!!
foreach ($data[$fieldName] as $key => $value) {
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $value
]);
}
} else { // SELECT FIELDS!!!
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $data[$fieldName]
]);
}
}
}
$user->userProfile->update(
[
'age_from_preference' => $request->age_from_preference,
'age_to_preference' => $request->age_to_preference,
'updated_at' => Carbon::now()
]
);
$request->user()->save();
return redirect()->route('profile.show', [$user->username]);
}
index.blade.php
<form action="{{ route('profile.update.interests.data') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group">
<span>Interessiert an</span>
{{-- wrong value - selected --}}
#isset($options)
#foreach($options as $name => $fieldData)
#if ($name == 'gender')
<div class="selectHolder">
<select name="{{ $name }}">
<option selected="true" disabled="disabled" value="" style="display:none">bitte auswählen</option>
#foreach($fieldData['data'] as $value => $label)
<option value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'selected' : '') : '' }}>
{{ $label }}
</option>
#endforeach
</select>
</div>
<?php
unset($options[$name]);
?>
#endif
#endforeach
#endisset
</div>
<div class="form-group">
<span>Im Alter von</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_from_preference ?? "" }}" name="age_from_preference">
<span>Jahren bis</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_to_preference ?? "" }}" name="age_to_preference">
<span>Jahren</span>
</div>
{{-- wrong value - checked --}}
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name.'-'.$value }}" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset
<div class="form-group">
<label for="" class="textBold">Button</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
code for $options variable
public static function getProfileLookingForDisplayOptions()
{
$options = [
'gender' => ['id' => 1, 'label' => "Interessiert an"],
'looking_for' => ['id' => 2, 'label' => ""]
];
$data_options = [];
foreach ($options as $field => $value) {
$data_options[$field]['data'] = Value::fieldValues($field);
$data_options[$field]['label'] = $options[$field];
if (!in_array($field, ['gender', 'looking_for'])) {
$data_options[$field]['data'][100] = "Doesn't matter";
}
}
//dd($data_options);
return $data_options;
}
If I understand your problem correctly, to deal with multiple checkboxes on PHP you need to add [] to its name property. That way, PHP knows it should interpret theses values as an array.
Also, your input name is not matching with $data[$fieldName].
Do it like this:
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name }}[]" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }} id="{{$name}}-{{ $value }}">
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset
Hi all am trying to do validations for a text field which is depends on other selected value .there is two columns buyer and reference number.so the validation is when i select particular names in buyer column then the reference must be required.
Below is my code
model::
public static $rules = array(
'delivery_contact_no' => 'required|numeric',
'external_ref_number' => 'required',
);
controller::
$check = false;
if ($_POST["user"] == '11Street') {
$check = true;
if (Input::get('external_ref_number') == "") {
$rules = array(
'external_ref_number' => 'required'
);
$messages = array(
'external_ref_number.required' => 'The External Reference Number Must be required ',
);
}
if ($check) {
$validator = Validator::make(Input::all(), $message);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
}
}
I am inserting input data like below:
$get = array(
'user' => trim($_POST["user"]),
'external_ref_number' => trim(Input::get('external_ref_number')),
);
so the validation is when I select particular names in buyer column then the reference must be required. below is view code
view::
<div class="form-group #if ($errors->has('user')) has-error #endif">
{{ Form::label('user', 'Buyer *', array('class'=> 'col-lg-2 control-label')) }}
<div class="col-lg-4">
{{ Form::text('user', Input::old('user'), array('class'=> 'form-control', 'autofocus' => 'autofocus', 'readonly' => 'readonly')) }}
{{ $errors->first('user', '<p class="help-block">:message</p>') }}
<input type="hidden" id="user_id" name="user_id">
</div>
<div class="col-xs-1">
<div class="input-group">
<div class="input-group-btn">
<span class="pull-left"><button id="selectUserBtn" class="btn btn-primary selectUserBtn" href="/transaction/ajaxcustomer"><i class="fa fa-plus"></i> Select Buyer</span>
</div>
</div>
</div>
</div>
<div class="form-group required {{ $errors->first('external_ref_number', 'has-error') }}">
{{ Form::label('external_ref_number', 'External reference number ', array('class' => 'col-lg-2 control-label')) }}
<div class="col-lg-4">
{{ Form::text('external_ref_number', $orderMappedInfo['external_ref_number'], ['placeholder' => 'External reference number', 'class' => 'form-control']) }}
{{ $errors->first('external_ref_number', '<p class="help-block">:message</p>') }}
</div>
</div>
The validation code which I wrote is not working. Please help me to solve this issue.
I am trying to do validations for a text field which is depends on other selected value.
There are two columns buyer and reference number.
so the validation is when i select particular names in buyer column then the reference must be required.
I have 2 form blade.php to get data and save into database. But I am doing a one to many relationship where there is one bear and many fish
But I don't know how to do it properly, previously I used this:
$bear = Bear::create(['Name' => $request->input('name_of_bear')]);
$bear->fishes()->create(['type_of_fish' => $fishType);
But it is only for 1 page, but what if I have 2 page, what do I need to do? Do I use associate, flash, session or something else to save the data into the database?
If possible can I also have some example for reference. Thank you
page1.blade.php:
{!! Form::open(['url' => 'page1/submit']) !!}
<div class="form-group">
{{Form::label('Name', 'Name of Bear ')}}
{{Form::text('Name', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('bear_type', 'Type of Bear ')}}
{{Form::text('bear_type', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::submit('Next', ['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
Controller for page1:
public function submit(Request $request)
{
$data = array();
$data['Name'] = $request->Name;
$data['bear_type'] = $request->bear_type;
$BearDetails = bear::create($data);
return redirect('http://test.dev/page2');
}
page2.blade.php
{!! Form::open(['url' => 'page2/submit']) !!}
<div class="form-group">
{{ Form::label('type_of_fish','Type of fish bear eat')}}
<input type="checkbox" id="inlineCheckbox1" name="type_of_fish[]" value="Salmon"> Salmon
<input type="checkbox" id="inlineCheckbox2" name="type_of_fish[]" value="Sardine"> Sardine
</div>
{{ Form::label('fish_location','Where is the fish located near at?')}}
<input type="checkbox" id="inlineCheckbox1" name="fish_location[]" value="Canyon"> Canyon
<input type="checkbox" id="inlineCheckbox2" name="fish_location[]" value="Rainforest"> Rainforest
</div>
{!! Form::close() !!}
</div>
<div class="form-group">
{{Form::submit('Submit', ['class' => 'btn btn-primary'])}}
</div>
Controller for page2:
$test = array();
$test['fish_location'] = $request->fish_location;
$test['type_of_fish'] = $request->type_of_fish;
$bear = bear::create($data);
$fish = fish::create($test);
$fish->user_particular()->associate($bear);
$fish->save();
return ('thank you');
}
bear model:
class bear extends Eloquent
{
protected $primaryKey = 'id';
public function fishs() {
return $this->hasMany('App\fish,'bear_id');
}
}
fish model:
class fish extends Eloquent
{
protected $fillable = array('name', 'bear_id');
// DEFINE RELATIONSHIPS
public function bears() {
return $this->belongsTo('App\bear);
}
}
I'm trying to write a simple site that can write and read of a simple mysql database, using Laravel, but I've run into a full stop as Laravel doesn't seem to be recognising my model. Either that or I am doing something wrong.
My model:
class Submission extends Eloquent
{
public static $timestamps = true;
protected $fillable = array('location', 'twitter', 'instagram', 'website');
}
My form:
#extends('layout')
#section('content')
{{ Input::old('twitter') }} <br />
{{ Input::old('instagram') }} <br />
{{ Input::old('website') }} <br />
{{ Form::open(array('url' => '/submission', 'files' => true)) }}
<div class="form-group">
{{ Form::label('twitter', 'Twitter') }}
{{ Form::text('twitter', '', array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('instagram', 'Instagram') }}
{{ Form::text('instagram', '', array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('website', 'Website') }}
{{ Form::text('website', '', array('class' => 'form-control')) }}
</div>
{{ Form::button('Submit image', array('class' => 'btn btn-success', 'type' => 'submit')) }}
<input type="hidden" name="post" value="yes">
{{ Form::close() }}
#stop
My controller:
public function postView()
{
$submission = new Submission;
$submission->twitter = Input::get('twitter');
$submission->instagram = Input::get('instagram');
$submission->website = Input::get('website');
$submission->save();
return Redirect::to('submission')->withInput();
}
My database looks like: id location twitter instagram website created_at updated_at
I know that my database config is correct as I can retrieve information using DB::table('submissions')->get(); so from what I can tell it's Laravel that's not recognising my model?
EDIT:
Turns out that changing public static $timestamps = true; to public $timestamps = true; fixed it.
Does this works :
DB::table('submissions')->get();
as it should return everything in the table. If it works then Eloquent can't find your table you can try to put that in your model:
protected $table = 'submissions';
It will define explicitly the table name in the model, even if it seems correct in your case
Otherwise you need to tell what exactly laravel answers when you made a request.
Do you have an error message in your browser ?
Do you have an error message in your log file (check the app/storage/logs folder)
Is your database configuration ok ? (app/config/database.php)
Did you create the table using a laravel migration ?
Hope it helps