Livewire checkboxes selected by default - laravel

What I would like :
By default check all checkboxes
Get the value sheet id for later
First issue :
Is it possible to sort / order them by id ?
Because for the moment it orders them by the order of check.
screenshot 2
If someone can help me I would be glad thanks :D
Here is my view :
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="{{$loop->index}}" wire:model="selectedBoxes" type="checkbox" value="{{$loop->index}}" checked/>
<label for="{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach
Here are the results when I dd($sheets) :
^ array:4 [▼
0 => "All ValueRAM FURY"
1 => "Non-ECC ValueRAM"
2 => "All FURY"
3 => "KSM (Server Premier)"
]
Here is my component :
public $sheets = [];
public $selectedBoxes = [];
...
public function readExcel()
{
...
$data = [];
// Return an import object for every sheet
foreach($import->getSheetNames() as $index => $sheetName)
{
$data = $import->getSheetNames();
$this->sheets = $data;
}
}
Website view :
screenshot 1

welcome to StackOverflow! You could remove the checked tag from your select and let wire:model do it's thing:
public $sheets = [
0 => "All ValueRAM FURY",
1 => "Non-ECC ValueRAM",
2 => "All FURY",
3 => "KSM (Server Premier)"
];
// wire:model will ensure that all are checked by default.
public $selectedBoxes = [true, true, true, true];
and in your view:
(Take a look at the wire:model property and the checked attribute is gone)
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="sheet-{{$loop->index}}"
wire:model="selectedBoxes.{{ $loop->index }}"
type="checkbox"
value="{{$loop->index}}" />
<label for="sheet-{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach

Thanks to Laisender I finded what I wanted.
What changed in my component :
public $counter = 0;
...
foreach($import->getSheetNames() as $index => $sheetName)
{
$data = $import->getSheetNames();
$this->sheets = $data;
array_push($this->selectedBoxes, "$this->counter");
$this->counter += 1;
}
My view :
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="sheet-{{$loop->index}}" wire:model="selectedBoxes.{{$loop->index}}" type="checkbox" value="{{$loop->index}}"/>
<label for="sheet-{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach

Related

Property [costo] does not exist on this collection instance

i need to print the price of a service, but can't find the column with the price.
maybe I'm doing something wrong with relationships, but I can't figure it out on my own
database:
Controller:
public function details(Request $request,$id){
$datax = [
'category_name' => 'apps',
'page_name' => 'calendar',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$evento = Eventos::find($id);
$servicio = \App\Models\Eventos::select("servicio_id")->where('servicio_id', $evento->id)->get('servicio_id');
$event = Eventos::find($id);
$event->asistencia = $request->asistencia;
$event->cancelado = $request->cancelado;
$event->save();
return view("evento",[
"event" => $event,
"servicio" => $servicio
])->with($datax);
}
blade.php
<div class="input-group mb-4">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="text" value="{{$servicio->costo}}" class="form-control col-md-3" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text"></span>
</div>
</div>
I need to print the "costo" column in relation to service_id
help please
you can use laravel elequent relationship one to one.
if you have this two Servicio.php & Evento.php in App/Models or whatever your models name is, only replace your models in below code do this:
1-
in App/Models/Servicio.php define this relationship:
public function evento()
{
return $this->hasOne(Evento::class);
}
in App/Models/Evento.php define this relationship:
public function servicio()
{
return $this->belongsTo(Servicio::class);
}
now in controller add this:
$evento = Eventos::where('id' , $id)->with('servicio')->first();
in blade use this:
<input type="text" value="{{$evento->servicio->costo}}" >
2- also you can do this but i suggest you the first one:
only in your Codes change this:
$servicio = \App\Models\Servicio::where('id', $evento->servicio_id)->first();

Laravel use sync on a many to many that includes a multiple extra fields

I'm trying to use sync on a many to many that includes a status and a comment. I can sync the applications without status and comment just fine.
NewUserAccount Model
public function applications()
{
return $this->belongsToMany('App\Application', 'new_user_account_applications', 'new_user_id')->withPivot('application_comment', 'status');
}
Application Model
public function newUserAccounts()
{
return $this->belongsToMany('App\NewUserAccount', 'new_user_accounts_applications', 'new_user_id')->withPivot('application_comment', 'status');
}
My NewUserAccountController
public function store(StoreRequest $request)
{
$userAccount = NewUserAccount::create(array_merge(
$request->all(),
['submitted_by' => $requester->id],
['start_date' => Carbon::parse($request->input('start_date'))],
['account_expires' => $request->accountExpires('newAccountExpireDate')],
['company_id' => $requester->company_id],
['username' => $request->manuallyAssignId()]
));
// Here I sync applications and include application comment and status
$userAccount->applications()->sync($request->applications, ['application_comment' => $request->application_comment, 'status' => 0]);
....
}
My pivot showing status and comment correctly
My form. Here is where I'm not sure how to handle the comment and get it to save with each application pivot record.
#foreach($applications as $application)
<label class="k-checkbox">
<input value="{{ $application->id }}" name="applications[]" type="checkbox">{{ $application->application_name }} <span></span>
</label>
<div class="form-group col-lg-4 mb-3">
<label>Comments</label>
<textarea name="application_comment[]" class="form-control" rows="2"></textarea>
</div>
#endforeach
First, you need to set the correct index for the application_comment attribute in your textarea. It's needed to correctly determine the comment for each application.
#foreach($applications as $application)
...
<textarea name="application_comment[{{ $application->id }}]" class="form-control" rows="2"></textarea>
...
#endforeach
Then, you just need to format your data to:
$userAccount->applications()->sync([
application_id_1 => ['application_comment' => 'comment for application_id 1'],
application_id_2 => ['application_comment' => 'comment for application_id 2'],
...
]);
So, here it is
$applications = collect($request->applications)->mapWithKeys(function ($appId) use ($request) {
return [$appId => [
'application_comment' => $request->input('application_comment')[$appId],
'status' => 0,
]];
});
$userAccount->applications()->sync($applications);

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'score' cannot be null

Controller
public function getScore(Request $request, $id)
{
// $scores = Criteria::find($id);
$contestants = Contestant::find($id);
foreach ($request->criteria as $id => $criteria){
$criteriaModel = Score::find($id);
$scores = new Score();
$scores->judge_name = $request->input('judge_name');
$scores->contestant = $contestants->name;
$scores->criteria = $criteriaModel->criteria;
$scores->score = $scores->score;
$scores->save();
}
return redirect('/tabulation')->with('status', 'Score saved!');
}
Blade
#foreach ($criterias as $criteria)
<div class="form-group col-md-6">
<label for="{{$criteria->name}}">{{$criteria->name}} </br> (0 - {{$criteria->points}})</label>
<input type="text" name="criteria[{{$criteria->id}}][criteria]" value="{{$criteria->name}}" hidden>
<input type="text" name="score[{{$criteria->id}}][score]" class="form-control" placeholder="Input score" required>
</div>
#endforeach
Form field names can contain brackets to store multiple properties for a single name:
#foreach ($criterias as $criteria)
<div class="form-group col-md-6">
<label for="{{$criteria->name}}">{{$criteria->name}} </br> (0 - {{$criteria->points}})</label>
<input type="text" name="criterias[{{$criteria->id}}][name]" value="{{$criteria->name}}" hidden>
<input type="text" name="criterias[{{$criteria->id}}][points]" class="form-control" placeholder="Input score" max="{{$criteria->points}}" name="score" required>
</div>
#endforeach
The above form would result the $request->criterias variable containing the following value:
array:2 [▼
1 => array:2 [▼
"name" => "test"
"points" => "dd"
]
2 => array:2 [▼
"name" => "tes22t"
"points" => "sdsd"
]
]
This value can be used in the controller for creating multiple scores:
foreach ($request->criterias as $id => $criteria){
$criteriaModel = Criteria::find($id);
$scores = new Score();
$scores->judge_name = $request->input('judge_name');
$scores->contestant = $contestants->name;
$scores->criteria = $criteriaModel->name;
$scores->score = $criteria->points;
$scores->save();
}
First of all you have to change the name of your input to be an array like so:
<input type="text" name="criteria[]" value="{{$criterias->name}}" hidden>
and in your controller you have to loop through the inputs:
foreach ($request->input('criteria') as $criteria){
$scores = new Score();
$scores->judge_name = $request->input('judge_name');
$scores->contestant = $contestants->name;
$scores->criteria = $request->input('criteria');
$scores->score = $request->input('score');
$scores->save();
}

Problems with Laravel Pivot Table

I am working on a medical lab application in laravel where I have the following tables:
1. Test table: This is a table which stores all the information related to medical tests:
2: Checkup: This is a page which contains all the patient information along with the tests he/she takes.
This is the test page:
This is the Checkup page where the tests and their results are selected:
Here can be many tests and user can check any number of them and will write the result of the test in the textfield below the checkbox.
I get this data in the controller like below code and save it to the database:
$this->validate($request,
[
'patient_name' => 'required|max:50',
'patient_age' => 'required',
'gender' => 'required',
'patient_type' => 'required',
'technition_id' => 'required',
'result' => 'required',
'test' => 'required',
'amount' => 'required'
]);
if( ($request->patient_type == 2) && ($request->doctor_id==0) )
{
return redirect()->back()->withInput(Input::all())->withErrors(['message' => 'Please select a valid Doctor.']);
}
$checkup = new Checkup;
$checkup->patient_name = $request->patient_name;
$checkup->patient_age = $request->patient_age;
$checkup->gender = $request->gender;
$checkup->patienttype_id = $request->patient_type;
$checkup->technition_id = $request->technition_id;
if(isset($request->doctor_id))
{
$checkup->doctor_id = $request->doctor_id;
}
$checkup->amount = $request->amount;
// $checkup->result = $request->result;
$checkup->save();
$tests =[];
$tests = $request->test;
$results =[];
$results = $request->result;
//$checkup->tests()->attach($tests->id, ['result' => $result]);
$sync_data = [];
for($i = 0; $i < count($tests); $i++)
$sync_data[$tests[$i]] = ['result' => $results[$i]];
$checkup->tests()->sync($sync_data);
Session::flash('success', 'The record was successfully saved.');
return redirect()->route('checkups.index');
Now the problem is that when I check all the checkboxes and write the result of all the tests then it is fine but when I select some and leave some of them then it gives error and the error comes because the result textbox for the unchecked test is empty.
This is the case when I select one test and leave the others:
When I check on test and write the result of it and then var_dump both test and result arrays i get the below output:
In the above image we can see that the test array contains one item because only one checkbox was checked but the result array contains two items and the first one is NULL which belongs to the unchecked checkbox.
This is the view file of the checkboxes and the textfields:
{{ Form::label('tests', 'Tests Taken') }}
#foreach(App\Test::all() as $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[]" type="text" class="form-control">
</div>
#endforeach
<div class="form-group">
{{ Form::label('amount', 'Amount') }}
{{ Form::text('amount', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{Form::button('<i class="fa fa-save"> Save</i>', ['type' => 'submit', 'class' => 'btn btn-success'])}}
</div>
{!! Form::close() !!}
Please help me on this and show me how to insert the pivot table data properly to the system.
Thanks in advance for any help.
Try this..
In your blade file :
#foreach(App\Test::all() as $index => $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[{{ $index }}]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[{{ $index }}]" type="text" class="form-control">
</div>
#endforeach
Instead of the for loop you can use foreach lopp.
$sync_data = [];
foreach($tests as $index => $value) {
if(!empty($results[$index]) {
$sync_data[$value] = ['result' => $results[$index]]
}
}
$checkup->tests()->sync($sync_data);

Laravel return old input of checkbox array

Edit: my $id contains an array
#php($ids = array('Fruit','Vegetables')
I just want to display the old input of my checkbox and textarea when the page returns with errors based on my validations.
Here is the form elements. I tried using the old(method) but its not working for me.
<form method = "post" action = "tomyController">
<input type = "text" name = "vendor" >
#foreach($ids as $id)
<input type = "checkbox" name = "check[{{$id}}][0]" value = "0">
<input type = "checkbox" name = "check[{{$id}}][1]" value = "1">
<textarea name = "remarks[{{id}}]"></textarea>
#endforeach
</form>
I tried the How to show old data of checkbox in Laravel? but didnt work on mine.
Here is how i implemented it.
<form method = "post" action = "tomyController">
#foreach($ids as $id)
<input type = "checkbox" name = "check[{{$id}}][0]" value = "0"
#if(is_array(old('check[$id][0]')) && in_array(0, old('check[$id][0]'))) checked #endif)>
<input type = "checkbox" name = "check[{{$id}}][1]" value = "1"
#if(is_array(old('check[$id][1]')) && in_array(1, old('check[$id][1]'))) checked #endif)>
<textarea name = "remarks[{{id}}]">{{ old('remarks[$id]') }}</textarea>
#endforeach
</form>
My controller code is here.
public function store(Request $request) {
$post = $request->all();
$validator = Validator::make($request->all(), [
"vendor" => "required",
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput($post);
}
else
#my other codes
}
dd($request)
Change your form to the following-
<form method = "post" action = "tomyController">
#foreach($ids as $id)
<input type = "checkbox" name = "check[{{$id}}][0]" value = "0"
#if(is_array(old('check['.$id.']')) && (0==old('check['.$id.'][0]'))) checked #endif>
<input type = "checkbox" name = "check[{{$id}}][1]" value = "1"
#if(is_array(old('check['.$id.']')) && (1== old('check['.$id.'][1]'))) checked #endif>
<textarea name = "remarks[{{$id}}]">{{ old('remarks['.$id.']') }}</textarea>
#endforeach
</form>

Resources