Save options radios or checkbox - laravel

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}}"/>

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

Livewire binding model radio button error

i'm trying to build a polls system using livewire but i got some errors
here is my blade
#foreach ($questions as $index => $question)
<div class="row">
<div class="box-header with-border">
<i class="fa fa-question-circle text-black fs-20 me-10"></i>
<h4 class="box-title">{{ $question->title }}</h4>
</div>
<div class="box-body">
<div class="demo-radio-button">
#foreach ($answers as $key => $answer)
<input wire:model="question{{ $question->id }}" type="radio"
id="answer{{ $question->id }}{{ $key }}"
class="radio-col-primary" value="{{ $key }}">
<label
for="answer{{ $question->id }}{{ $key }}">{{ $answer }}</label>
#endforeach
#error('question')
<div class="text-danger text-bold">{{$message}}</div>
#enderror
</div>
</div>
</div>
#endforeach
my Livewire class
public $question = [];
public function render() {
$category = PollCategory::findOrFail($this->category->id);
$subCategories = PollSubCategory::where('poll_category_id', $category->id)->get();
$answers = PollAnswer::all();
return view('livewire.polls', compact('category', 'subCategories', 'answers'));
}
The Error is
Property [$question41] not found on component: [polls]
Any help please ?
you did it wrong way,
solution:
<input wire:model="question.{{ $question->id }}"
$question{{ $question->id }} equal $question41
$question.{{ $question->id }} equal to $question[41]
that's why u receive error Property [$question41] not found on component

Laravel save related data in database

I want to save question_id in answer table using post form
I tried to use foreach or functions but i always got null data
Controller
public function store(Request $request, Survey $survey)
{
$request->validate([
'answer' => 'required',
]);
$survey->option_name = unserialize($survey->option_name);
$answers = new Answer([
'answer' => $request->get('answer'),
'commentaire' => $request->get('commentaire'),
'user_id' => auth()->id(),
'last_ip' => request()->ip(),
'question_id' => $survey->questions,
'survey_id' => $survey->id,
]);
$answers->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
answers table
question table's row :
id
survey_id
title
timestamp
I got always null data or i tried using where but i got errors like id index doesn't exists...
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="form-group">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#empty
<span class='flow-text center-align'>Nothing to show</span>
#endempty
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}

Laravel : save radio group with difference key

I want to save radios group in database with different question_id
I tried to use form with radio's input have name=answer
controller :
public function store(Request $request, Survey $survey)
{
$question = \App\Question::where('survey_id', '=' , $survey->id)->get();
$request->validate([
'answer'=>'required'
]);
$arr = $request->except('_token');
$newAnswer = new Answer();
$newAnswer->answer = request()->get('answer');
foreach ($survey->questions as $key=>$question){
$newAnswer->question_id = $question->id;
}
$newAnswer->user_id = Auth::id();
$newAnswer->last_ip = request()->ip();
$newAnswer->survey_id = $survey->id;
$newAnswer->commentaire = request()->get('commentaire');
givePoint(new VoteAdded($newAnswer));
$newAnswer->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
view :
<div id="Create" class="col-12" style="display:none;">
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
<div class="text-center">
<img class="rounded"
src="https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"
alt="Grapefruit slice atop a pile of other slices" />
</div>
<hr>
#foreach ($survey->questions as $question)
<p class="flow-text">Question {{ $zero++}} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer[{{$question->id}}]" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#endforeach
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}
</div>
Tables :
i have already made it :
Answer table = id, survey_id , question_id , answer . commentaire ,
timestamp
Survey table : id title ...
question table : id , suvey_id , option_type , options
I got in my database a array: ["question_id" = "value"]
what a want is for example i have 2 questions , in my database i want to save 2 row with some survey id but different question id
could you help me to do that ?
-Since 1 survey can have many questions create a separate table for questions like survey_questions
-You can insert in multiple tables at the same time by writing insert queries for the survey and survey questions table separately and wrapping it in a transaction. In Laravel, you can do something like
try{
DB::transaction();
//insert in survey table
//insert in survey questions table
DB::commit();
} catch(\Exception $e){
DB::rollback()
}

How to display selected tags in select option value in laravel?

This is my Post Create View
<div class="col-lg-12">
<form action="{{ route('admin.post.store') }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ old('title') }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ old('body') }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-success btn-block">Publish</button>
</form>
</div>
Tags have many to many relationship.
Here I can select many tags, but in the post edit view I cant see the selected tags that selected by me in the post create view.
I want to show selected tags in select option value and edit theme.
post update methods:
public function edit(Post $post)
{
$tags = Tag::all()->pluck('name', 'id');
$cats = Category::all();
return view('admin.post.edit', compact(['post', 'cats', 'tags']));
}
public function update(Post $post, Request $request)
{
$this->validate($request, [
'title' => 'required|min:3|max:255',
'slug' => 'nullable|string',
'image' => 'sometimes|mimes:jpeg,bmp,png,jpg,gif',
'body' => 'required',
'category' => 'nullable',
'views' => 'nullable',
'tags' => 'nullable',
]);
$post->title = $request->title;
$post->slug = $request->slug;
$post->body = $request->body;
$post->category_id = $request->category;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldfilename = $post->image;
$post->image = $filename;
Storage::delete($oldfilename);
}
$post->save();
$post->tags()->sync($request->tags, false);
Session::flash('update', 'Post Updated Successfully');
return redirect()->route('admin.post.index');
}
post edit view:
<div class="col-lg-12">
<form action="{{ route('admin.post.update',$post->id) }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
{{ method_field('patch') }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ $post->title }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select class="js-example-basic-single form-control" name="tags[]" id="tags" multiple="multiple">
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ $post->body }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option <?php if ($cat->id == $post->category_id) {
echo 'selected';
} ?> value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary btn-block">Edit</button>
</form>
</div>
here:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}</option>
#endforeach
</select>
</div>
how can I pass selected post tags from database and show theme here and edit them.
I am using select2 plugin
In select2 I should pass data in jQuery:
$('.js-example-basic-single').select2().val({{ json_decode($post->tags()->getRelatedIds()) }}).trigger('change');
but it doesnt work :(
and I get this error
Method Illuminate\Database\Query\Builder::getRelatedIds does not exist. (View: C:\Users\M0RT3Z4\Desktop\MyBlog\resources\views\admin\post\edit.blade.php
Please help me, Thanks!
You have put the code in wrong place:
Try this:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}" {{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $name }}</option>
#endforeach
</select>
</div>

Resources