In my page I can have multiple addresses, but the user can only select one address.
The problem I'm having is that both my radio buttons are being saved instead of just one.
So if the user has 2 addresses then only one should have selected = 1 and the other address should be selected = 0, but at the moment both address = 1.
I haven't been able to only have 1 address selected and saved as such in the database. I know that I'm passing the ID of the selected radio button through, but I was hoping to have this happen.
E.G: When the user saves their first address that is then saved as their selected address (selected = 1) and any other addresses they add after that will be (selected = 0).
If they change their mind and want their second address to be the one they use then the select it and that will then become like this, address 1 (selected = 0) and address 2 will become (selected = 1).
I hope this made sense. If it didn't please let me know.
My form
#foreach($addresses as $address)
<div class="col-lg-4">
<form id="address-radio" action="{{ route('account.post.addresses.radio', $address->id) }}" method="post">
#csrf
<div class="form-check">
<input type="radio" class="form-check-input" name="address_option" id="address_{{ $address->id }}" {!! $address->selected == '1' ? 'checked' : '' !!}>
<label for="address_{{ $address->id }}" class="form-check->label">
#if(!empty($address->complex))
{{ $address->complex }} <br>
#endif
{{ $address->address }} <br>
{{ $address->suburb }} <br>
{{ $address->city }} <br>
{{ $address->province }} <br>
{{ $address->postal_code }} <br>
</label>
</div>
</form>
</div>
#endforeach
<script>
$(document).ready(function(){
$('input[type="radio"]').on('change', function(){
$(this).closest("form").submit();
})
})
</script>
and this is my function
public function postAddressesRadio(Request $request, $id)
{
$selected = Address::findOrFail($id);
$user_id = Auth::user()->id;
$not_selected = $selected->where('id', '!=', $id)
->where('user_id', $user_id)->get();
foreach($not_selected as $selected)
{
$selected->selected = "0";
}
if($request->address_option == 'on'){
$selected->selected = '1';
}
$selected->save();
return redirect()->back()->with('success', 'Address was updated');
}
So I've managed to do it. I'm not sure if there is a better way but this works.
In my function I did
public function postAddressesRadio(Request $request, $id)
{
$address = Address::findOrFail($id);
$user_id = Auth::user()->id;
$addresses = Address::where('user_id', $user_id)->get();
foreach($addresses as $address)
{
if($address->id == $id)
{
$address->selected = "1";
}else{
$address->selected = "0";
}
$address->save();
}
Related
I have a dropdown in a livewire component that I'm using a change event to enable/disable a second input field. The change event is working, and it's sent to the server, and updated in the database, however, after the change event fires, it immediately changes the dropdown selected value back to the original one. I can't figure out why it's doing that.
Here's the code in my blade view:
<div class="row">
<div class="mb-3 col-md-4">
<x-input.group label="Legal Entity" for="legal_entity_type_id" :error="$errors->first('companyDetail.legal_entity_type_id')">
<x-input.select wire:model.defer="companyDetail.legal_entity_type_id" wire:change="entitySelected" id="legal_entity_type_id" for="legal_entity_type_id" label="Legal Entity">
#foreach ($legalEntities as $entity)
<option name="{{ $entity->name }}" id="{{ $entity->id }}" value="{{ $entity->id }}" wire:key="{{ $entity->id }}" #if (isset($companyDetail->legal_entity_type_id) && $companyDetail->legal_entity_type_id === $entity->id) selected #endif>
{{ $entity->name }}
</option>
#endforeach
</x-input.select>
</x-input.group>
</div>
<div class="mb-3 col-md-5">
<x-input.group label="Legal Entity If Other" for="legal_entity_description_if_other" :error="$errors->first('companyDetail.legal_entity_description_if_other')">
<x-input.text wire:model.defer="companyDetail.legal_entity_description_if_other" isDisabled="{{ !$enableOtherLegalEntity }}" id="legal_entity_description_if_other" name="legal_entity_description_if_other" value="{{ $companyDetail->legal_entity_description_if_other ?? '' }}" />
</x-input.group>
</div>
</div>
Here's the component code:
class CompanyDetail extends Component
{
public LocationDetail $companyDetail;
public $legalEntities;
public $smsTypes;
public $enableOtherLegalEntity;
protected $rules = [
'companyDetail.legal_entity_type_id' => 'required|exists:legal_entity_types,id',
'companyDetail.legal_entity_description_if_other' => 'required_if:legal_entity_type_id, ==, 6',
'companyDetail.sms_type_id' => 'required|exists:sms_types,id',
'companyDetail.rent_amount' => 'numeric',
'companyDetail.ein' => 'numeric|max:999999999'
];
public function mount(LocationDetail $companyDetail)
{
$this->companyDetail = $companyDetail;
$this->smsTypes = SmsType::all();
$this->legalEntities = LegalEntityType::all();
$this->enableOtherLegalEntity = ($this->companyDetail['legal_entity_type_id'] == 6);
}
public function render()
{
return view('livewire.locations.company-detail');
}
public function entitySelected()
{
$this->enableOtherLegalEntity = ($this->companyDetail['legal_entity_type_id'] == 6);
}
public function save()
{
$this->validate();
$this->companyDetail->save();
$this->companyDetail->refresh();
$this->dispatchBrowserEvent('closeModal');
}
}
I am trying to create a multiple select filter. When I use whereIn for the id I get this error
Invalid parameter number (SQL: select * from stations where id in (16128))
With 16128 being one of the two id's selected for that query. It works fine with a manual given array so I am not sure what the problem is. I also tried with array_values but I get the same result.
<label for="" class="col-md-3">Daypart</label>
<div class="container-checkbox">
#foreach($dayparts as $id => $daypart)
<div wire:key="{{ $daypart->id }}">
<input type="checkbox" id="{{ $daypart->daypart_name }}" name="{{ $daypart->daypart_name }}" wire:model="filters.dayparts.{{ $daypart->id }}" wire:click="filtru({{ $daypart->id }})" />
</div>
#endforeach
</div>
public function filtru($id){
$this->filters['dayparts'] = array_filter($this->filters['dayparts']);
$dayp = DaypartStation::whereIn('daypart_id', array_keys($this->filters['dayparts']))->get();
foreach($dayp as $day){
$this->arr[]=$day->station_id;
}
$toate = Station::whereIn('id', [$this->arr])->get();
//dd(Station::whereIn('id', $this->arr)->get());
//dd(Station::whereIn('id', [array_values($this->arr)])->get());
// dd(Station::whereIn('id', [16576, 16776, 16376])->get());
}
public function render()
{
return view('livewire.create-workbooks-table', [
'stations'=> Station::
when($this->filters['dayparts'], function($query){
$query->whereIn('id', [$this->arr]);
})
->search($this->search)
->orderBy($this->sortBy, $this->sortDirection)
->latest()
->Paginate($this->perPage),
]);
}
I believe you should change
$toate = Station::whereIn('id', [$this->arr])->get();
to
$toate = Station::whereIn('id', $this->arr)->get();
since $this->arr is already an array
Please I'd like to refresh same component after form submit. There is an if statement that allows the the form to display in the component. I'd like to refresh the whole component so as not to show the form again after submit.
I already tried emit but I don't think it works for same component.
Livewire component
<?php
namespace App\Http\Livewire;
use App\Lesson;
use App\Question;
use App\QuestionsOption;
use App\TestsResult;
use Livewire\Component;
class LessonTest extends Component
{
public $test_result;
public $lesson;
public $test_exists;
public array $question = [];
//protected $listeners = ['testDone' => 'render'];
public function mount($test_exists, $lesson, $test_result)
{
$this->lesson = $lesson;
$this->test_exists = $test_exists;
$this->test_result = $test_result;
}
public function lessonTest()
{
$lesson = Lesson::where('slug', $this->lesson->slug)->firstOrFail();
$answers = [];
$test_score = 0;
foreach ($this->question as $question_id => $answer_id) {
$question = Question::find($question_id);
$correct = QuestionsOption::where('question_id', $question_id)
->where('id', $answer_id)
->where('correct', 1)->count() > 0;
$answers[] = [
'question_id' => $question_id,
'option_id' => $answer_id,
'correct' => $correct,
];
if ($correct) {
$test_score += $question->score;
}
/*
* Save the answer
* Check if it is correct and then add points
* Save all test result and show the points
*/
}
$test_result = TestsResult::create([
'test_id' => $this->lesson->test->id,
'user_id' => \Auth::id(),
'test_result' => $test_score,
]);
$test_result->answers()->createMany($answers);
$this->reset(['question']);
$this->emit('testDone');
}
public function render()
{
return view('livewire.lesson-test');
}
}
Livewire Blade View
<div>
#if ($test_exists)
<hr />
<h3>Test: {{ $lesson->test->title }}</h3>
#if (!is_null($test_result))
<div class="alert alert-info">Your test score: {{ $test_result->test_result }} /
{{ $lesson->test->questions->count() }}</div>
#else
<form wire:submit.prevent='lessonTest' action="{{ route('lessons.test', [$lesson->slug]) }}"
method="post">
{{ csrf_field() }}
#foreach ($lesson->test->questions as $question)
<b>{{ $loop->iteration }}. {{ $question->question }}</b>
<br />
#foreach ($question->options as $option)
<input type="radio" wire:model='question.{{ $question->id }}'
name="questions[{{ $question->id }}]" value="{{ $option->id }}" />
{{ $option->option_text }}<br />
#endforeach
<br />
#endforeach
<button class="btn btn-success btn-lg refresh" type="submit">Submit</button>
</form>
#endif
<hr />
#endif
</div>
Thank You. I got it solved, I forget that I passed the test result from the controller before, so I had to recall the test_result and also the test_exist inside the lessonTest action.
$this->test_result = TestsResult::where('test_id', $this->lesson->test->id)
->where('user_id', \Auth::id())
->first();
$this->test_exists = true;
Let me explain with a couple of word my problem.
On my controller i have this line:
$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
This works for existing users, but when i try to create new ones i receive
Call to a member function tasks() on null
Can i with something like this or what do you suggest ?
if(!is_null($tasks))
$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
}
This i my show function on controller
public function show(){
$user = Auth::user();
if(!$user)
return redirect('/')->withErrors(config('constants.NA'));
$countries = Country::all()->lists('name', 'id')->toArray();
$profile = $user->profile;
$student = $profile->student;
// Tasks showed on students profile
if ($student->group) {
$tasks = $student->group->tasks()
->orderBy('created_at', 'desc')
->withPivot('id')
->get();
}
// Classmates
if ($student->group) {
$classmates = $student->group->students()
->where('id', '!=', $student->id)
->get();
}
// Activated books
$books = Auth::user()->books()->orderBy('grade_id', 'asc')->get();
if(!is_null($student->group))
$iTasks = $student->group->tasks->count();
else {
$iTasks = 0;
}
$iTodos = $user->todos->count();
return view('student.profile.show',compact('user','profile', 'countries', 'iTasks', 'iTodos', 'tasks', 'classmates', 'books'));
}
This is my show view, for the tasks
<div class="tab-pane <?php if(isset($tab) && $tab == 'timeline'): ?> active <?php endif; ?>" id="timeline">
#if($tasks->count())
<div class="timeline">
#foreach($tasks as $task)
<!-- TIMELINE ITEM -->
<div class="timeline-item">
<div class="timeline-badge">
<div class="timeline-icon">
<i class="mdi mdi-clipboard-text font-red-intense"></i>
</div>
</div>
<div class="timeline-body">
<div class="timeline-body-arrow"> </div>
<div class="timeline-body-head">
<div class="timeline-body-head-caption">
<span class="timeline-body-title font-blue-madison">
{{ $task->professor->profile->user->name }}
</span>
<span class="timeline-body-time font-grey-cascade">ju ca caktuar një detyrë të re.</span>
</div>
</div>
<div class="timeline-body-content">
<span class="font-grey-cascade">
{{ $task->pivot->comment }}
</span>
</div>
<hr>
Lenda: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->subject->name }}</span>
<div class="pull-right">
Krijuar më: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->created_at->format(Config::get('klasaime.date_format')) }}</span>
</div>
</div>
</div>
<!-- END TIMELINE ITEM -->
#endforeach
</div>
#else
<div class="alert">
Ju nuk keni asnje detyrë të caktuar!
</div>
#endif
</div>
Looks to me like you haven't added the student to a group yet, or that somehow hasn't been persisted. If you have added the student to a group after creating and saving the student, try this:
$student->load('group')
Before running:
$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
I'll need to see more of your code to give a more accurate answer. But the error you're getting is related to the ->group, of your student, not your student itself.
Do a simple check to see if the group exists and then carry on with whatever action you need to perform.
// controller
$tasks = null;
if ($student->group) {
$tasks = $student->group->tasks()
->orderBy('created_at', 'desc')
->withPivot('id')
->get();
}
// view
#if($tasks)
{{ $tasks->id }}
#else
No tasks found
#endif
Edit : In your controller add $tasks = null; and $classmates = null; at top. And in your view change #if($tasks->count()) to #if($tasks). I'm not sure where your use the classmates variable, but add a check to see if it's null before you use it.
Im interested in giving users the option to add articles to custom lists that they create. (like youtube's playlist feature).
I want to know how to show a 'checked' checkbox next to a list if the article already exists within it, so they don't add it twice.
My database tables:
list : | id | person_id | list_name | list_desc
list_ref : | id | list_id | article_id
My code for displaying lists.
$lists = Lists::where('person_id', Auth::user()->person_id)->get();
#foreach($lists as $list)
<input type="checkbox" id="available_list" value="{{ $list->id }}">
{{ $list->list_name }}
#endforeach
If anyone could help me understand the code to query the two tables to see if list already used || list is available.
You could use a raw expression in conjunction with a left join like this:
$lists = DB::table('list')->
leftJoin('list_ref', 'list_ref.list_id', '=', 'list.id')->
select(DB::raw('list.*, IF(list_ref.list_id = list.id, 1, 0) used'))->
where('person_id', Auth::user()->person_id)->
get();
The above uses a join to figure out which list rows has a corresponding key in the list_ref table. The result will contain a field called used that will tell if the entry has a reference in the list_ref table.
You should now be able to generate you form like this:
#foreach($lists as $list)
<input type="checkbox" id="available_list" value="{{ $list->id }}" {{ $list->used ? "CHECKED" : "" }}>
{{ $list->list_name }}
#endforeach
First crate class, here is example for facility
class HotelFacilities
{
public $facility_id;
public $facility;
public $status;
}
Get all data
$facilities = Facility::all();
Get user related data
$user_facilities = UserFacility::where('user_id', 3)->get();
//Here you add status
$array_hotel_facility = array();
for($i=0; $i<count($facilities); $i++)
{
$obj_hotel_facilities = new HotelFacilities;
$obj_hotel_facilities->facility_id = $facilities[$i]['id'];
$obj_hotel_facilities->facility = $facilities[$i]['facility'];
$obj_hotel_facilities->status = false;
for($j=0; $j<count($user_facilities); $j++)
{
if($user_facilities[$j]->facility_id == $facilities[$i]->id)
{
$obj_hotel_facilities->status = true;
}
}
//Pass this array to view
$array_hotel_facility[$i] = $obj_hotel_facilities;
}
//Pass to view
return view('extranet.view_facilities')->with('facilities', $array_hotel_facility);
//Generate UI like this
#foreach($facilities as $facility)
<div class="form-group col-md-3">
<div class="form-group">
<label>
<input type="checkbox" class="minimal" name="facilities[]" value="{{ $facility->facility_id }}" <?php if($facility->status){echo "checked";} ?>>
{{ $facility->facility }}
</label>
</div>
</div>
#endforeach