Save checkbox values into database - php

I am designing a form where the user can fill up their particulars and submit it to the database. For the most part, it works. There is one part with the form about the driving license class, it does not work. A person can have multiple driving licenses so I made that into a checkbox field. However, when the user selects two or more driving licenses, only the lastly selected driving license appears in the database. So, if a person selects Class1 firstly and then selects Class2, only Class2 appears in the database.
How can I include all the driving licenses selected by the user into one database column?
I have attached the code below.
form.blade.php
#extends('layout.basiclayout')
#section('content')
<p>page 1/7</p>
{!! Form::open(['url' => 'form/submit']) !!}
<h3 style= 'text-decoration: underline'>PERSONAL PARTICULARS - </h3>
<div class="form-group">
{{Form::label('Name/NRIC', 'Name AS PER NRIC/PASSPORT: ')}}
{{Form::text('Name/NRIC', '', ['class' => 'form-control', 'placeholder' => 'eg: John Smith'])}}
</div>
{{-- start of Driver`s License --}}
<p>
<div class="editfield">
<div class="radio">
<span><b>Do you have a Driver`s license?</b></span>
<div id="Driver_licenseID">
<label><input type="radio" name="Driver_license" id="yesid" value="Yes" onclick="document.getElementById('Driver_license').style.display='block'">Yes</label>
<label><input type="radio" name="Driver_license" id="noid" value="No" onclick="document.getElementById('Driver_license').style.display='none'">No</label></div>
</div>
</div>
<div class="editfield" id="Driver_license" style="display:none">
<input type="checkbox" name="Driver_license_class" id="Driver_license_class1" value="Class1">Class 1
<input type="checkbox" name="Driver_license_class" id="Driver_license_class2" value="Class2">Class 2
<input type="checkbox" name="Driver_license_class" id="Driver_license_class2A" value="Class2A">Class 2A
<input type="checkbox" name="Driver_license_class" id="Driver_license_class2B" value="Class2B">Class 2B <br>
<input type="checkbox" name="Driver_license_class" id="Driver_license_class3" value="Class3">Class 3
<input type="checkbox" name="Driver_license_class" id="Driver_license_class3A" value="Class3A">Class 3A
<input type="checkbox" name="Driver_license_class" id="Driver_license_class3C" value="Class3C">Class 3C
<input type="checkbox" name="Driver_license_class" id="Driver_license_class3CA" value="Class3CA">Class 3CA <br>
<input type="checkbox" name="Driver_license_class" id="Driver_license_class4" value="Class4">Class 4
<input type="checkbox" name="Driver_license_class" id="Driver_license_class4A" value="Class4A">Class 4A
<input type="checkbox" name="Driver_license_class" id="Driver_license_class5" value="Class5">Class 5
</div>
</p>
{{-- End of Driver`s License --}}
<div class="form-group">
{{Form::submit('Next Page', ['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
#endsection
migration file
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePersonalInfosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('personal_infos', function (Blueprint $table) {
$table->increments('id');
$table->String('Name');
$table->String('Driver_license');
$table->String('Driver_license_class');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('personal_infos');
}
}
controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PersonalInfo;
class PersonalInfoController extends Controller
{
public function submit(Request $request){
$this->validate($request,[
'Name/NRIC' => 'required',
]);
$PersonalParticulars = new PersonalInfo;
$PersonalParticulars->Name = $request->input('Name/NRIC');
$PersonalParticulars->Driver_license = $request->input('Driver_license');
$PersonalParticulars->Driver_license_class = $request->input('Driver_license_class');
$PersonalParticulars->save();
return redirect('http://formapplication.dev/page2');
}
}

You have to set it up as an array by adding [] in the name of the checkbox.
Change all <input type="checkbox" name="Driver_license_class" to:
<input type="checkbox" name="Driver_license_class[]"
Now, you will receive the results as an array, instead of just the single value. To process the values into the database, you could do mulitple things depending on how you want it to be saved.
You could loop trough the values by using the following code:
if(isset($_POST['Driver_license_class'])){
foreach($_POST['Driver_license_class'] as $license){
echo $license; // Outputs the selected license
}
}
Or you can implode the values with the desired delimiter:
implode(", ", $_POST['Driver_license_class'])
This will return the selected results as comma seperated values.
Edit
As requested, here is where you need to change your code after adding the []:
$PersonalParticulars->Driver_license_class = implode(", ", $request->input('Driver_license_class'));

Change the name of checkboxes in your blade to
name="Driver_license_class[]"
So that you can get the selected licenses as an array in your php code.
To save an array to a field in database, you need to save it in CSV format:
$PersonalParticulars->Driver_license = implode(',', $request->input('Driver_license'));
Alternatively you may save data in JSON format
$PersonalParticulars->Driver_license = json_encode($request->input('Driver_license'));

Related

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'male' in 'field list' laravel 9

to be honest idk what's wrong here in my code but i still receive this error i see all the solution here but nothing happen , is the problem in the type="radio"? i try to change it to type="checkbox" but it still appears an error """ datatype of checkbox-> boolean
my blade file : form ->
<form action="{{url('reserveinfo')}}" method="POST" enctype="multipart/form-data" >
#csrf
<!-- ******** input user data to reserve ******** -->
<div class="MaleFemale">
<div class="Male">
<input type="radio" name="male" id="ML">
<label for="ML">Male</label>
</div>
<div class="Female">
<input type="radio" name="female" id="FML">
<label for="FML">Female</label>
</div>
</div>
<div class="FullName">
<input type="text" name="fullname" placeholder="Full name">
</div>
<div class="PatientEmail">
<input type="email" name="email" placeholder="Email">
</div>
<div class="TestBirthday">
<div class="Test">
<p>Test PCR</p>
<div>
<label for="TSTFILE">
<img src="../Resources/File.png" for="TSTFILE">
Add file</label>
<input type="file" name="testpcr" id="TSTFILE">
</div>
</div>
<div class="Birthday">
<label for="Birthday">Birthday</label>
<input type="date" name="date">
</div>
</div>
<div class="DoctopPres">
<p>Doctor prescription</p>
<div>
<label for="DctrPres">
<img src="../Resources/File.png" for="DctrPres">
Add file</label>
<input type="file" name="doctorpres" id="DctrPres">
</div>
</div>
<!--########## Send request ########## -->
<div class="Reserve">
<a href="../HtmlFiles/Reserve-3-.html">
<button>Reserve</button>
</a>
</div>
Controllers code :
public function reserveinfo(Request $request){
$data = new reserveinfo;
$data->male=$request->Male;
$data->female=$request->female;
$data->fullname=$request->fullname;
$data->email=$request->email;
$data->birthday=$request->date;
$test_pcr=$request->file('testpcr');
$imagename=time().'.'.$test_pcr->getClientoriginalExtension();
$request->testpcr->move('Text-PCR-of-users',$imagename);
$data->$test_pcr=$imagename;
$Doctor_prescription=$request->file('doctorpres');
$imagename2=time().'.'.$Doctor_prescription->getClientoriginalExtension();
$request->doctorpres->move('Doctor-prescription-of-users',$imagename2);
$data->doctorpres=$imagename2;
if(Auth::id()){
$data->user_id=Auth::user()->id;
}
$data->save();
return redirect()->back();
}
routes :
Route::get('/reserve1_view',[UserController::class,'addview']);
Route::get('/reserve2_view',[UserController::class,'addview2']);
Route::post('/reserveinfo',[UserController::class,'reserveinfo']);
migrations code :
public function up()
{
Schema::create('reserve2s', function (Blueprint $table) {
$table->id();
$table->boolean('male')->nullable();
$table->boolean('female')->nullable();
$table->string('fullname')->nullable();
$table->string('email')->nullable();
$table->string('test_pcr')->nullable();
$table->string('birthday')->nullable();
$table->string('Doctor_prescription')->nullable();
$table->string('user_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('reserve2s');
}
};
and get this error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'male' in 'field list
models code :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class reserveinfo extends Model
{
use HasFactory;
}
""" nothing add to models """
thanks for reading this XD
Try this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class reserveinfo extends Model
{
use HasFactory;
protected $table = 'reserve2s';
}
I recommend you read the Laravel manual about Eloquent's naming convention.
Eloquent Model Conventions
In your second error you are using the value of the variable $test_pcr as the attribute name. Just remove the $.
// Change this
$data->$test_pcr=$imagename;
// to
$data->test_pcr=$imagename;
// Change this
$data->doctorpres=$imagename2;
// to
$data->Doctor_prescription=$imagename2;
Remembering that you should read about Eloquent to understand how this integration works with the model and the database table.

How to store multiple checkbox values to database in Laravel?

I need to store checkbox values into the database. I have tried so many examples, but still am not able to do that, Here I will give you my code and give me the solution for this.
My Blade File
<div class="form-group row">
<label for="hobbies" class="col-md-4 col-form-label text-md-right">Hobbies</label>
<div class="col-md-6">
<input type="checkbox" name="hobbies[]" value="Readbooks"/> Readbooks
<input type="checkbox" name="hobbies[]" value="Games"/> Games
<input type="checkbox" name="hobbies[]" value="Music"/> Music
#if ($errors->has('hobbies'))
<span class="text-danger">{{ $errors->first('hobbies') }}</span>
#endif
</div>
</div>
My Controller File
public function postRegistration(Request $request)
{
$data = $request->all();
$check = $this->create($data);
return redirect("login")->withSuccess('Great! please login.');
}
public function create(array $data)
{
return User::create([
'hobbies' => $data->implode([',', (array) $data->get('hobbies')]),
]);
}
Error:Call to a member function implode() on array
This is not how you use the implode method. And like the error says; you try to call a method on an array, because $data is an array and not an object.
And last, $data->get('hobbies') will also cause you problems, because the get() helper is not working on an array.
This is what you need:
return User::create([
'hobbies' => implode(',', (array) $data['hobbies']),
]);
When you have inputs like:
<input type="checkbox" name="hobbies[]" value="Readbooks"/> Readbooks
<input type="checkbox" name="hobbies[]" value="Games"/> Games
<input type="checkbox" name="hobbies[]" value="Music"/> Music
The POST data received by the server includes hobbies as an array. You can confirm this by inspecting the received request in your controller:
public function postRegistration(Request $request) {
dd($request);
}
Since $request->hobbies is already an array, there is no need to cast it with (array).
In the code you've shown, you are trying to implode() your hobbies. implode() generates a string, so if the hobbies field you are trying to populate in the database is a string, you simply need to implode that received array of hobbies:
// Will generate a string like: "Readbooks,Music"
implode(',', $request->hobbies);
Putting it into your code:
public function create($data) {
return User::create(['hobbies' => implode(',', $data->hobbies)];
}

Laravel 6 looking for tips on how to approach a problem with form switches

I started working on my first Laravel 6 web app about 2 months ago.
I've been stuck for far too long on this & I'm looking for some tips on what angle from should I look at this problem:
Problem
There's a form in my blade view that has a textarea for user input, 3 switches/checkboxes, a button & a disabled textarea field for the output (just a placeholder for the output at the moment).
This is how the form looks like
The user can paste a list of domains in the textarea input field & depends on which switches/checkboxes are checked, the request (which is now an array thanks to preg_split in the controller) must go through all checked switches/checkboxes logic. I look at these switches like they are filters.
Question
Basically I'm in a never-ending search for any tips on how should I approach defining those switches. I've looked into form request validation, but that doesn't seem to be needed in solving this problem (I know I will use it later to finish up & not leave any loose ends in user inputs fields).
Now, I have a class(ListsCleaner.php) method(filters) that is called in the controller to respond to the request from the view & I think I'm moving the right way, I just don't know how to start writing each switch logic(switch1, switch2, switch3) in there:
class ListsCleaner
{
protected $domains;
function __construct($domains)
{
$this->domains = $domains;
}
public function filters()
{
// Should I write all 3 switches/checkboxes logic here?
}
}
My controller.php
public function filter(Request $request)
{
$domains = preg_split('/\\s/', $request->input('domains'));
dd ($domains);
return new ListsCleaner($domains);
}
dd ($domains);
array:5 [▼
0 => "website1.com"
1 => ""
2 => "website2.com"
3 => ""
4 => "website3.com"
]
My blade.php view
<form class="col s12 center-align" method="get" enctype="multipart/form-data" action="{{ route('filters') }}">
{{csrf_field()}}
<div class="row">
<!-- Switches -->
<div class="switch col 4 valign-wrapper">
<label>
<input checked type="checkbox" name="Switch1" value="true">
<span class="lever"></span>
gTLDs
</label>
</div>
<div class="switch col 4 valign-wrapper">
<label>
<input checked type="checkbox" name="Switch2" value="true">
<span class="lever"></span>
Competitors
</label>
</div>
<div class="switch col 4 valign-wrapper">
<label>
<input checked="checked" type="checkbox" name="Switch3" value="true">
<span class="lever"></span>
Blogspam Sites
</label>
</div>
</div>
<div class="row">
<div class="col s6 input-field">
<textarea name="domains" id="batch_requests" class="materialize-textarea" rows="5" oninput="changedValue()"></textarea>
<label for="batch_requests">Enter URLs separated by space or line break.</label>
</div>
<div class="col s6 input-field">
<textarea disabled name="domains_cleaned" class="materialize-textarea" rows="5" oninput="changedValue()"></textarea>
</div>
</div>
<div class="row">
<div class="col s6 left-align">
<button type="submit" class="btn btn-large waves-effect waves-light white-text">Clean Websites</button>
</div>
</div>
</form>
And lastly, my full ListsCleaner class
namespace App\Lists;
class ListsCleaner
{
protected $domains;
function __construct($domains)
{
$this->domains = $domains;
}
public function filters()
{
// Should I write all 3 switches/checkboxes logic here?
}
}
If I were you, I'd create three classes in \App\Models\Filters, and named them accordingly (class Filter1, class Filter2). Then on each class I'd have a filter($list) method that contains the logic.
On the controller, I'd have a property:
$filters = [
'filter1' => App\Models\Filters\Filter1,
'filter2' => App\Models\Filters\Filter2,
'filter3' => App\Models\Filters\Filter3,
];
Then finally on the controller action you could loop through those and check which ones were selected by user:
foreach($this->filters as $filterName => $class) {
if($request->has($filterName)) {
$list = (new $class)->filter($list);
}
}
That would allow you to run all the three (or more) filters while having their logic in a separate place, which is good for code structure.
As a bonus, you can make Filter1, Filter2 and Filter3 extend a base class App\Models\Filters\AbstractFilter, which would hold common data/methods these filters share.

Cant be able to fetch name from the table model and display it in the view using laravel

I am trying to fetch the subject_name from the table subject using the subject_id I stored in the users table but whenever I try to do that I get this error. Any help ?
The relationship is ONE USER CAN ONLY HAVE ONE SUBJECT REGISTERED AND ONE SUBJECT CAN BE SELECTED BY MANY USERS SO ITS ONE TO MANY RELATIONSHIP
`Illuminate \ Database \ QueryException (42S02)
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myunimentor_database.subject_user' doesn't exist (SQL: select `subjects`.*, `subject_user`.`user_id` as `pivot_user_id`, `subject_user`.`subject_id` as `pivot_subject_id` from `subjects` inner join `subject_user` on `subjects`.`id` = `subject_user`.`subject_id` where `subject_user`.`user_id` = 1)
Previous exceptions
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myunimentor_database.subject_user' doesn't exist (42S02)`
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\UserType;
use App\Subject;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'type', 'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getAllUsers() {
return User::all();
}
public function userTypes()
{
return $this->belongsTo('App\Users');
}
public function subjects()
{
return $this->belongsToMany('App\Subject');
}
}
Subject Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
use App\SubjectKeyword;
class Subject extends Model
{
protected $fillable = [
'subject_name',
];
public function users()
{
return $this->hasMany('App\User');
}
public function subjectKeywords()
{
return $this->hasMany('App\SUbjectKeyword');
}
}
#extends('layout.dashboard')
#section('title', 'Add Subjects')
#section('content')
<p> You can only add <font color='#5FCF80'>1 Subject</font> <br/>
follow by 5 keywords for Non Mentors to search you. </br/>
<font color='#5FCF80'> <b>HAPPY MENTORING!</b></font></p>
<br/>
Controller
$users = User::where('id', Auth::user()->id)->first();
echo $users;
$users->subject_id = $s1;
echo Auth::user()->subjects->subject_name;
die();
View
#section('content1')
<p>Mentor Subject:
{{ Auth::user()->subject->subject_name }}
</p>
<p> Specified Keywords:
#foreach($subjectKeywords as $sk)
<li> {{ $sk ['keyword_title1'] }} </li>
<li> {{ $sk ['keyword_title2'] }} </li>
<li> {{ $sk ['keyword_title3'] }} </li>
<li> {{ $sk ['keyword_title4'] }} </li>
<li> {{ $sk ['keyword_title5x'] }} </li>
#endforeach
</p>
<form class="form-horizontal" method="POST" role="form" action="/add-new-subject" >
{{ csrf_field() }}
<div class="form-group" data-rule="required">
<label>Subject Titles</label> <br/>
<select id="ddselect" name='subject_name' class="signup" required >
<option value=""> Select Subject to Monitor </option>
#foreach($subjectDetails as $s)
<option id={{ $s['id'] }} name={{ $s['id'] }} value={{ $s['id'] }}>{{ $s['subject_name'] }}</option>
#endforeach
</select>
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" name="k1" class="signup-control form" id="k1" placeholder="Keyword 1"/>
<div class="validation"></div>
<input type="text" name="k2" class="signup-control form" id="k2" placeholder="Keyword 2"/>
<div class="validation"></div>
<input type="text" name="k3" class="signup-control form" id="k3" placeholder="Keyword 3"/>
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" name="k4" class="signup-control form" id="k4" placeholder="Keyword 4"/>
<div class="validation"></div>
<input type="text" name="k5" class="signup-control form" id="k5" placeholder="Keyword 5"/>
<div class="validation"></div>
</div>
</div>
<br/>
<div class="col-xs-12">
<!-- Button -->
<button type="submit" id="submit" name="submit" class="form contact-form-button light-form-button oswald light">Select Subject</button>
</div>
</form>
#endsection
#endsection
In your User model Relation should be belongsTo()
public function subject(){
return $this->belongsTo('App\Subject','subject_id','id');
}
Now you can access your subject name as Auth::user()->subject->subject_name
As you said one user have only one subject so User belongsTo only one subject.
Subject can have multiple users it means HasMany.
User model -> belongsTo with subject
Subject Model -> HasMany with users
Please check here for more info. https://laravel.com/docs/5.8/eloquent-relationships#one-to-many
Your belongsToMany relationship is causing the problem. It causing laravel to think there is a pivot table named subject_user but sadly there is no pivot table. So change your relationship to belongsTo
public function subject(){
return $this->belongsTo('App\Subject','subject_id');
}
Here is another problem. In your User Model in your fillable array there is no subject_id. So subject_id won't be saved in database. Add this to your fillable array.

Cant get values of checkboxes in codeigniter

Im trying to insert multiple checkboxes but cant get their values in codeigniter 2
this is my code in View
<!-- Multiple Checkboxes (inline) -->
<div class="form-group">
<div class="col-md-4">
<label class="checkbox-inline" for="checkboxes-0">
<input type="checkbox" name="checkboxes[]" id="checkboxes-0" value="22">
Пентхаус
</label>
<br>
<!-- Text input-->
<div class="form-group">
<div class="col-md-8">
<input id="cena" name="cena[]" type="text" placeholder="Въведи цена" class="form-control input-md">
</div>
</div>
<label class="checkbox-inline" for="checkboxes-1">
<input type="checkbox" name="checkboxes[]" id="checkboxes-1" value="21">
Гараж/Паркомясто
</label>
<br>
<!-- Text input-->
<div class="form-group">
<div class="col-md-8">
<input id="cena" name="cena[]" type="text" placeholder="Въведи цена" class="form-control input-md">
</div>
</div>
This is my Model:
public function InsertCheckbox() {
$property_typesRequest = $this->input->post('checkboxes');
foreach($property_typesRequest as $value){
$this->db->insert_batch('property_type_details', $property_typesRequest);
}
}
in Controller i just use this:
$this->estate_m->InsertCheckbox();
And this going insert 0 in database, when i var_dump $property_typesRequest theres shows bool(false). I cant get values of checkboxes...
EDIT...
I have try to edit my code but still no result:
public function edit()/*this is controller */
{
$data=array('column_name'=>$this->input->post('checkboxes');
$result=$this->estate_m->InsertCheckbox($data);
if($result==true)
{
echo "Success";
}
else
{
echo "Fail";
}
}
public function InsertCheckbox($data) /*this is Model */
{
$this->db->insert('property_type_details', $data);
return ($this->db->affected_rows() != 1 ) ? false : true;
}
With this edited code always gives me Succes
Form submitted values should be in multi dimension array
To achieve that your form inputs should be in multi dimension.
For insert_batch() function, the array should be in multi dimension.
In array every key must be field names in db table and value must be the form input value.
So change the form structure like the below array.
array(
array(
'checkboxes' => 'checkboxe value' ,
'cena' => 'cena values'
),
array(
'checkboxes' => 'checkboxe value' ,
'cena' => 'cena values'
)
);
Form inputs should be like below:
<input name="data[1][checkbox_columnname]" type="checkbox" value="21">Пентхаус
<input name="data[1][textbox_columnname]" type="text">
<input name="data[2][checkbox_columnname]" type="checkbox" value="22">Гараж/Паркомясто
<input name="data[2][textbox_columnname]" type="text">
And the model should not have foreach loop.
Simply pass the data as below.
$data=$this->input->post('data');
$this->db->insert_batch('mytable', $data);
Please use this code in model.
public function InsertCheckbox() {
$property_typesRequest = $this->input->post('checkboxes');
foreach($property_typesRequest as $value){
$data['columnename'] = $value;
$this->db->insert('tablename', $data);
}
}
Hope it inserts into the database
Thank you

Categories