Laravel: How to save checkbox value - laravel

I get this error, when I submit the form
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'onloan' cannot be null
Please help. Sorry for the noob question. I've been searching but the examples are different.
edit.blade.php
<div class="form-group">
<input type="checkbox" class="" id="onloan" value="1" {{ $item->onloan == 1 ? 'checked' : '' }}>
<label for="onloan">On Loan</label>
</div>
controller
public function update(Request $request, Item $item)
{
$item->update([
'name' => $request->name,
'description' => $request->description,
'barcode' => $request->barcode,
'onloan' => $request->onloan //Not Working
]);
}

add name="onloan" on your input field, otherwise it won't pass data with form submit method.
<input type="checkbox" class="" name="onloan" id="onloan" value="1" {{ $item->onloan == 1 ? 'checked' : '' }}>
If you uncheck the checkbox, then it will send nothing with submit, so from your controller you can give a value (0) if value is not passed :
'onloan' => ($request->onloan) ? '1' : '0';
Or,
if(isset($request->onloan)) {
$onloan = "1";
} else {
$onloan = "0";
}
'onloan' => $onloan,

Related

Livewire checkboxes selected by default

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

Return Redirect Laravel

I want to return to the page with Link : localhost:8000/order/show/O1/T1.
O1 is $order->id_order and T1 is $trip->id_trip.
Here's my code.
Route::get('/order/show/{id_order}/{id_trip}', 'OrderController#show');
Route::get('/order/update_driver/{id_order}/{id_trip}', 'OrderController#update_driver');
Order Controller
public function show($id_order, $id_trip){
$trip = Trip::find($id_trip);
$order = Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->first();
$detail_order = Detail_Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->first();
$detail = Order::join('detail_order', 'order.id_order', '=', 'detail_order.id_order')
->where('order.id_order', $id_order)
->select('order.id_trip as order_trip',
'order.id_order as order_id',
'order.id_users as order_users',
'order.date_order as order_date',
'detail_order.id_seat as detail_seat',
'detail_order.users as detail_users')
->get();
$driver = Driver::all();
return view('travel.order.show', ['trip' => $trip, 'order' => $order, 'detail' => $detail, 'detail_order' => $detail_order, 'driver' => $driver]);
}
public function update_driver($id_order, $id_trip){
$driver = Input::get('id_users_driver');
Detail_Order::where('id_order', $id_order)
->update(['id_users_driver' => $driver]);
session()->flash('flash_success', 'Data has been updated');
return redirect('/order/show/{id_order}/{id_trip}');
}
View
<form method="get" action="/order/update_driver/{{ $order->id_order}}/{{ $order->id_trip}}">
<label>Driver</label>
<select class="form-control" name="id_users_driver" id="id_users_driver">
<option value=""> Driver </option>
#foreach($driver as $d)
<option value="{{$d->id_users}}"{{$detail_order->id_users_driver == $d->id_users ? 'selected' : ''}}>{{$d->name}}</option>
#endforeach
</select>
#if($errors->has('id_users_driver'))
<div class="text-danger">
{{ $errors->first('id_users_driver')}}
</div>
#endif
<input type="submit" class="btn btn-primary" value="Save">
</form>
It returned error Trying to get property 'id_order' of non-object.
Do you know how to make it return to localhost:8000/order/show/O1/T1? Thank you

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);

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);

codeigniter login validation not validating rules

am using codeigniter 3.0.4 .here this Here the action send to the controler(first.php)not validating anything it will turn to else statement and display login page again(as set as in redirect('welcome/login_page');). my register function in the same controller working good. what is the exact problem ..please help me to find it.thanks.
..............the controller(first.php).....
public function signup_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if($this->form_validation->run() ){
$user_id= $this->model_users->get_id($this->input->post('email'));
$user_status = $this->model_users->get_status($this->input->post('email'));
$data = array (
'user_id' => $user_id,
'email' => $this->input->post('email'),
'user_status' =>$user_status,
'is_logged_in' => 1
);
$this->session->set_userdata($data);
}
if ($this->session->userdata('user_status')=='0') {
redirect('main/admins');
}
elseif ($this->session->userdata('user_status')=='1') {
redirect('main/members');
}else{
redirect('welcome/login_page');
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in() ){
return TRUE;
} else {
$this->form_validation->set_message('validate_credentials', 'Invalid useername(email-id) or password. !');
return FALSE;
}
}
....the view(login.php)......
echo form_open("first/signup_validation");
echo'<div class="row">';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="email">Email<span></span></label>';
echo'<input type="text" class="form-control" id="email">';
echo'</div>';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="password">Password<span></span></label>';
echo'<input type="password" class="form-control" id="password">';
echo'</div>';
echo'</div>';
$data2 = array(
'class' => 'btn btn-default',
);
echo form_submit($data2, 'Login');
echo form_close('');
?>
echo '<input type="text" class="form-control" id="email">';
Your input elements don't contain a name attribute. The name is what's used as the identifier in the validation rule.
$this->form_validation->set_rules('email'... // <- 'email' is the name attribute
Do this...
echo'<input type="text" class="form-control" id="email" name="email">';

Resources