How to store multiple checkbox values to database in Laravel? - php

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

Related

How to display the value in a readonly input field in laravel

So, in my project, a user needs to register first before logging-in. I am trying to display their first, middle and last name. But, I am having a problem since multiple data are displayed on my input field. What is the correct query? Here is my controller code
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$input.="<input value={$first_name->seq_id}>{$first_name->first_name}</input>";
}
return $input;
}
public function step1()
{
$users = UserModel::all();
$data['optStatus']=$this->get_civil_status();
$data['displayFirstName']=$this->get_first_name();
return view ("enrollment-steps.step1", $data);
}
Here is the blade file
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="firstName" class="col-sm-3 text-right control-label col-form-label">First
Name</label>
<div class="col-sm-9">
<input class="form-control" type="text" id='firstName' readonly value="{!! $displayFirstName !!}" >
</div>
</div>
</div>
this is the data that it displays
There is some confusing stuff going on there, but you probably want
<input class="form-control" type="text" id='firstName' readonly value="{{ $data['displayFirstName'] }}" >
which will display the value with the key 'displayFirstName' in the $data array.
dd is your friend, use this in your blade file to see what you have in your $data variable.
{{dd($data)}}
In you controller bind the data's in a single variable, then show it in the blade
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$input.="<input value={$first_name->seq_id}>{$first_name->first_name}</input>";
}
return $input;
}
Instead of this, do something like this:
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$displayname = $first_name->seq_id . $first_name->first_name;
$input.="<input value="{$displayname}"</input>";
}
return $input;
}

update checkbox value in laravel 8 (blade/ controller )

I'm beginner in laravel and I want to update multiple checkboxes in database ..
when I click at update button automatically my inputs show old value also my permissions are checked by old value to update it ..
relation between user and permission is manytomany .. I have another table named userpermissions who has id_user and id_permission
this is my update form in ( edit.blade.php)
<form action="{{ url('users/'.$user->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" id="name" required class="form-control" value="{{ $user->name }}">
#error('name')
<ul class="alert"><li class="text-danger">{{ $message }}</li></ul>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="email" required class="form-control" value="{{ $user->email }}">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
#foreach($permissions as $permission)
<input type="checkbox" name="data[]" value="{{ $permission->id }}"
<?php if( in_array($permission->id, $user->userPermissions->pluck('permission_id')->toArray())){ echo 'checked="checked"'; } ?>/>
{{ $permission->name }}
#if($loop->iteration % 3 == 0 ) <br> #else #endif
#endforeach
</div>
</div>
</div>
<div class="text-right mt-4">
<button type="submit" class="btn btn-primary"> Add</button>
</div>
</form>
and this is my controller where I think have a problem with methods :
edit function
public function edit(User $user)
{
$permissions = Permission::get();
return view('users.edit', compact('user','permissions'));
}
update function :
public function update(UserRequest $request,User $user)
{
$user->update(
$request->only('name', 'email')
);
$user->userPermissions()->save($request->input('data'));
return redirect()->back()->with('status','user updated !');
}
and this is my functio store :
public function store(UserRequest $request)
{
$this->validate($request, [
'name' => 'required',
'email'=>'required|email',
'password' => 'required|confirmed|min:6',
]);
$user = User::create(
$request->only('name', 'email', 'password')
);
$user->userPermissions()->createMany($request->input('data'));
return redirect()->back()->with('status','Utilisateur ajouté !');
}
Thanks for advance !
$user->userPermissions()->save($request->input('data'));
One important thing to understand here, is that save() on relation doesn't remove old values from pivot table, it just add more values to it(no distinction check). You need something like refresh functionality. Look at attaching\detaching or sync, second one is more convenient.
In first case before saving permissions you can do this
// remove all old permissions
$user->userPermissions()->detach();
// update them with new one
$user->userPermissions()->attach($request->input('data'));
In second case, which is less verbose then first one you just need to pass and array of permissions to user object.
// this will do both things which we did before
$user->userPermissions()->sync($request->input('data'))
But i encourage you to read the docs and ask questions after ;)
Another thing which i saw and its not related to the current topic is
$user->userPermissions->pluck('permission_id')->toArray()
you are using lazy load inside of foreach loop which means that on each iteration of the loop you are making a query to the database(N + 1 problem). You can preload/eager load userPermissions instead of loading them on a fly by declaring with relation in your User model like this
class User extends Model
{
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = ['userPermissions'];
...
}
and then in your User object will have userPermissions property which you can compare to permissions.
Hope that you get main idea and info was useful for you!

Save checkbox values into database

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

Laravel 5 validate cloned fields using form request

I have a form using cloneya jQuery plugin to clone form elements. The elements that will be cloned looks like so:
<div class="form-group">
<label for="name">Item name</label>
<input class="form-control" name="name[]" type="text">
</div>
<div class="form-group">
<label for="count">Item count</label>
<input class="form-control" name="count[]" type="text">
</div>
As you can see, each input will be an array instead of string. I want to validate those using Laravel Form Request. Here's my rules:
public function rules()
{
return [
'name' => 'required|between:3,50',
'count' => 'required|integer|min:1',
];
}
But that's not working. When I submitted the form, I got the following error message:
htmlentities() expects parameter 1 to be string, array given
I've been searching for solution, but can't find the appropriate one. Any suggestion would be appreciated!
Basically, in your rules() method, you need to determine how many name and count elements there are in the POST and then create rules for each of them:
public function rules()
{
$rules = [];
foreach ($this->request->get('name') as $index => $val) {
$rules['name.' . $index] = 'required|between:3,50';
}
foreach ($this->request->get('count') as $index => $val) {
$rules['count.' . $index] = 'required|integer|min:1';
}
return $rules;
}
Please check this post.

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