Multiple Checkbox Saving to DB 1 or 0 - laravel

Creating multiple question checkboxes and I need to send two possible cases 1 or 0 to the database. However, it always sends the last one I click as 1 all the others 0. So for example, if a user clicks/checks the first one and the last I want to send to the database both 1 and the other two unchecked 0.
Controller
<?php
public function create($request)
{
foreach ($request['options'] as $key => $option) {
Answer::create([
'question_id' => $this->get(),
'text' => $option,
'correct' => $request['correct'] == $key ? 1 : 0
]);
}
}
View
#for($i = 1; $i<=4; $i++)
<div class="form-group {{ $errors->has('options.'.$i) ? ' has-error': '' }}" id="option{{ $i }}">
<div class="checkbox col-xs-2 control-label" style="margin-top: -2px">
<label>
<input id="cc" type="checkbox" name="correct" value="{{$i}}" {{ $i==1 ? 'checked' : '' }} >
<!--
{!! Form::hidden('correct',0) !!}
{!! Form::checkbox('correct',1,false) !!}
-->
</label>
</div>
<div class="col-xs-8">
<input type="text" name="options[{{ $i }}]" value="{{ old('options.'.$i) }}"
class="form-control" placeholder="#lang('general.option') {{ $i }}">
#if($errors->has('options.'.$i))
<div class="col-xs-12"></div>
<span class="help-block">
<strong>{{ $errors->first('options.'.$i) }}</strong>
</span>
#endif
</div>
</div>
#endfor

Either mention array of control for checkbox as below
<input id="cc" type="checkbox" name="correct[]" value="{{$i}}" {{ $i==1 ? 'checked' : '' }} >
change name="correct" to name="correct[]"
OR
give different name to each checkbox using incremental variable like
name="correct" to name="correct_".$i

Related

Attempt to read property "social_media_channel_name" on string laravel

my controller
$id= Auth::guard('artist')->user()->id;
$profiles= Profile::where('id', $id)->get();
$profiless= Profile::findorFail($id);
return view('artists.profile_edit',compact('profiles','profiless'));
my model
protected $casts = [
'social_media_channel_name' =>'array',
'social_media_channel_link' =>'array',
];
my blade
#foreach($profiless as $key => $profiles)
<div class="col-md-6">
<input type="text" class="form-control mb-3 {{ $errors->has('social_media_channel_name') ? 'is-invalid' : '' }}" name="social_media_channel_name[]" value="{{$profiles->social_media_channel_name}}" placeholder="Social Media Channel Name">
</div>
#if($errors->has('social_media_channel_name'))
<div class="invalid-feedback">
{{ $errors->first('social_media_channel_name') }}
</div>
#endif
<div class="col-md-6">
<input type="text" class="form-control mb-3 {{ $errors->has('social_media_channel_link') ? 'is-invalid' : '' }}" name="social_media_channel_link[]" value="{{$profiles->social_media_channel_link}}" placeholder="Social Media Channel Link">
</div>
#if($errors->has('social_media_channel_link'))
<div class="invalid-feedback">
{{ $errors->first('social_media_channel_link') }}
</div>
#endif
#endforeach
here Attempt to read property "social_media_channel_name" on string laravel show error.how to solve
here Attempt to read property "social_media_channel_name" on string laravel show error.how to solve
There's a lot wrong with your code...
$profiles= Profile::where('id', $id)->get();
You're querying based on id, which should return a single row, but you're calling ->get() which returns a Collection... That's pointless.
$profiless= Profile::findorFail($id);
This is more correct, but that variable name is really bad.
#foreach($profiless as $key => $profiles)
You're looping over a single Model instance, which would make $key and $profiles both strings; you don't need this foreach at all. Additionally, you're overwriting the $profiles variable you're passing from the Controller via compact('profiles','profiless'));
Let's fix your code.
$id = auth()->guard('artist')->user()->id;
$profile = Profile::where('user_id', $id)->first();
// I assume `Profile` has a `user_id` column, you'd want to reference this instead of `id`
return view('artists.profile_edit', compact('profile');
profile_edit.blade.php:
<div class="col-md-6">
<input type="text" class="form-control mb-3 {{ $errors->has('social_media_channel_name') ? 'is-invalid' : '' }}" name="social_media_channel_name[]" value="{{ $profile->social_media_channel_name }}" placeholder="Social Media Channel Name">
</div>
#if($errors->has('social_media_channel_name'))
<div class="invalid-feedback">
{{ $errors->first('social_media_channel_name') }}
</div>
#endif
<div class="col-md-6">
<input type="text" class="form-control mb-3 {{ $errors->has('social_media_channel_link') ? 'is-invalid' : '' }}" name="social_media_channel_link[]" value="{{ $profile->social_media_channel_link }}" placeholder="Social Media Channel Link">
</div>
#if($errors->has('social_media_channel_link'))
<div class="invalid-feedback">
{{ $errors->first('social_media_channel_link') }}
</div>
#endif
Edit
If a User can have multiple Profiles, then you can do:
$id = auth()->guard('artist')->user()->id;
$profiles = Profile::where('user_id', $id)->get();
return view('artists.profile_edit', compact('profiles');
And include the loop in your view:
#foreach($profiles as $profile)
// The rest of the code would be the same
#endforeach

Show an attribute from other model in blade (Laravel)

I´ve got this exception in my blade template. I made a relation between my two models (RegisteredCourses y User) and I can see it works in the rest of Blade´s template, except form.blade.php
Trying to get property 'user' of non-object (View: C:\laragon\www\hr-english\resources\views\registeredCourse\form.blade.php) (View: C:\laragon\www\hr-english\resources\views\registeredCourse\form.blade.php)
My idea is to show in my blade template the name of the user, but I need in the value of input the correspondant user_id.
I don´t what is the correct approach to this problem.
<div class="form-group {{ $errors->has('course_id') ? 'has-error' : '' }}">
<label for="course_id" class="col-md-2 control-label">Course</label>
<div class="col-md-10">
<select class="form-control" id="course_id" name="course_id">
<option value="" style="display: none;" {{ old('course_id', optional($registeredCourse)->course_id ?: '') == '' ? 'selected' : '' }} disabled selected>Select course</option>
#foreach ($courses as $key => $course)
<option value="{{ $key }}" {{ old('course_id', optional($registeredCourse)->course_id) == $key ? 'selected' : '' }}>
{{ $course }}
</option>
#endforeach
</select>
{!! $errors->first('course_id', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('user_id') ? 'has-error' : '' }}">
<label for="status_course" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input class="form-control" name="user_id" type="text" id="user_id" value="{{ old('user_id', optional($registeredCourse->user->name)) }}" minlength="1" placeholder="Enter name here..."> <!--Problwm here-->
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('status_course') ? 'has-error' : '' }}">
<label for="status_course" class="col-md-2 control-label">Status Course</label>
<div class="col-md-10">
<input class="form-control" name="status_course" type="text" id="status_course" value="{{ old('status_course', optional($registeredCourse)->status_course) }}" minlength="1" placeholder="Enter status course here...">
{!! $errors->first('status_course', '<p class="help-block">:message</p>') !!}
</div>
</div>
Use the null coalescing operator: $registeredCourse->user->name ?? null instead of optional($registeredCourse->user->name) in your blade
UPS: Here's a demo showing how this works depending on whether $registeredCourse->user is set or not.

How to return validated value of ID in Laravel validation

So I have created looped generated radio-buttons:
<div class="custom-control custom-radio guest-form">
#foreach(config('const.res_site') as $id => $res)
<div class="form-radio">
<input class="custom-control-input" type="radio" onchange="otherResSite({{$id}})" id="{{$res}}" value="{{$id}}"
name="reservation_site" {{ old("reservation_site") == $id ? "checked" : "" }}>
<label for="{{ $res }}" class="custom-control-label">{{ $res }}</label>
</div>
#endforeach
<div class="otherField" id="ifOtherSite" class="otherSite" style="display: {{ old('reservation_site') == 4 ? 'display:inline-flex' : 'none' }}">
<input type='text' class="form-control" id='otherSite' name='otherSite' value="{{ old('otherSite', '') }}"><br>
</div>
</div>
#if ($errors->has('otherSite'))
<div class="form-group">
<p class="text-danger">{{ $errors->first('otherSite') }}</p>
</div>
#endif
const.php
'res_site' => [
0 => 'site1',
1 => 'site2',
2 => 'other',
],
This one is to validate the otherSite value if selected option is other. It now works well but the validation message returned is like this:
The other site field is required when reservation site is 2.
My validator is like this:
return [
'reservation_site' => ['required'],
'otherSite' => ['required_if:reservation_site,2'],
]
Now, how can I make its return message as
The other site field is required when reservation site is other
Is there any way I can do that?
Okay. If someone might need this someday, I did it this way:
<input class="custom-control-input" type="radio" id="{{$res}}" value='{{$id == 4 ? "other" : $id}}'>
and in my validation:
return [
'reservation_site' => ['required'],
'otherSite' => ['required_if:reservation_site,other'],
]

Laravel exists validation if the given value is not zero

This is my situation:
Assume I have a radio input in my html form which it's value must to exists in a table only IF user check one of them, else the value have to be zero
this my structure:
<div class="inputGroup">
<input id="first_change1" name="first_change" type="radio" value="{{ $game->teamOne->id }}" {{ old('first_change') == $game->teamOne->id ? 'checked="checked"' : '' }} />
<label for="first_change1" class="farsi">{{ $game->teamOne->name }}</label>
</div>
<div class="inputGroup">
<input id="first_change2" name="first_change" type="radio" value="{{ $game->teamTwo->id }}" {{ old('first_change') == $game->teamTwo->id ? 'checked="checked"' : '' }} />
<label for="first_change2" class="farsi">{{ $game->teamTwo->name }}</label>
</div>
<div class="inputGroup">
<input id="first_change3" name="first_change" type="radio" value="0" {{ old('first_change') == "0" ? 'checked="checked"' : '' }} />
<label for="first_change3" class="farsi">None of them</label>
</div>
#if( $errors->has('first_change'))
<h6 class="alert alert-danger farsi text-danger rtl text-right">
{{ $errors->first('first_change') }} <i class="fa fa-2x fa-arrow-up fleft" style="bottom: 5px !important;"></i>
</h6>
#endif
And this is my current validation for this field:
'first_change' => 'required|exists:fc_teams,id',
But I need something like this:
'first_change' => 'required|[IF VALUE IS NOT -0-; THEN]exists:fc_teams,id',
You could build your validation conditionally:
$first_change_validation = [
'required',
];
if ($request->get('first_change') == 0) {
$first_change_validation[] = 'exists:fc_teams,id';
}
And then use this array in your validation:
$this->validate($request, [
'first_change' => $first_change_validation,
]);

Save options radios or checkbox

I want to save radio from form in database but I get "on" in the database, I don't know why.
I tried to use HTML form with labels, radios and checkbox but I see in the database saving "on".
Controller :
public function store(Request $request, Survey $survey)
{
// remove the token
$arr = $request->except('_token');
foreach ($arr as $key => $value) {
$newAnswer = new Answer();
if (! is_array( $value )) {
$newValue = $value['answer'];
} else {
$newValue = json_encode($value['answer']);
}
$newAnswer->answer = $newValue;
$newAnswer->question_id = $key;
$newAnswer->user_id = Auth::id();
$newAnswer->survey_id = $survey->id;
$newAnswer->save();
$answerArray[] = $newAnswer;
};
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
view :
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
#forelse ($survey->questions as $key=>$question)
<p class="flow-text">Question {{ $key+1 }} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="input-field col s12">
<input id="answer" type="text" name="{{ $question->id }}[answer]">
<label for="answer">Answer</label>
</div>
#elseif($question->question_type === 'textarea')
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input name="{{ $question->id }}[answer]" type="radio" id="{{ $key }}" />
<label for="{{ $key }}">{{ $value }}</label>
</p>
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="something{{ $key }}" name="{{ $question->id }}[answer]" />
<label for="something{{$key}}">{{ $value }}</label>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#empty
<span class='flow-text center-align'>Nothing to show</span>
#endforelse
{{ Form::submit('Submit Survey', array('class'=>'btn waves-effect waves-light')) }}
{!! Form::close() !!}
You forgot to give a value attribute to your checkbox and radio inputs, for example something like this:
<input name="{{ $question->id }}[answer]" type="radio" id="{{ $key }}" value="{{ $key}}"/>
<input type="checkbox" id="something{{ $key }}" name="{{ $question->id }}[answer]" value="{{ $key}}"/>

Resources