I have a form where i collect data from checkboxes.
Here is my form
<div class="col-md-6">
<textarea name='description[]' placeholder="{{ Lang::get('core.description') }}" rows='6' id='description' class='form-control' required>
{{ $day->description }}
</textarea>
<div class="col-md-12">
<?php $meal = explode(",", $day->meal); ?>
<label class='checked checkbox-inline'>
<input type='checkbox' name='meal[]' value ='B' class='' #if(in_array('B',$meal))checked #endif />
{{ Lang::get('core.breakfast') }}
</label>
<label class='checked checkbox-inline'>
<input type='checkbox' name='meal[]' value ='L' class='' #if(in_array('L',$meal))checked #endif />
{{ Lang::get('core.lunch') }}
</label>
<label class='checked checkbox-inline'>
<input type='checkbox' name='meal[]' value ='D' class='' #if(in_array('D',$meal))checked #endif />
{{ Lang::get('core.dinner') }}
</label>
</div>
</div>
And this is my controller
$day = $_POST['day'] ;
for($i=0; $i < count($day); $i++)
{
$dataDays = array(
'day' => $_POST['day'][$i],
'title' => $_POST['title'][$i],
'meal' => implode(',', (array)$_POST['meal'] ),
'description' => $_POST['description'][$i],
'cityID' => $_POST['cityID'][$i],
'tourID' => $id
);
\DB::table('tour_detail')->insert($dataDays);
}
I get all the data right except meal. What am i missing with implode? I tried one without array as implode(',', $_POST['meal'] ), this didnt help. I tried implode(',', $_POST['meal'][$i] ) but i got an error. Can you please tell me how can i get the right data from checkboxes.
thanks
Related
I am very new to Laravel. I am currently doing a Laravel project where a person can submit a proposal. The Laravel version I'm using is Laravel Framework 8. I divided the proposal form into 7 pages. I also have 7 tables in the database. So the data of each page will be saved into each of the tables. 1 page = 1 table. This means I also have 7 models. In conclusion, I have 7 views, 7 controllers, 7 models, and 7 tables (if this is not a good practice please tell me)
Here is an example of my code
Route
web.php
Route::get('/form/details', [App\Http\Controllers\Lect\Form\Step1Controller::class, 'createStepOne'])->name('form.create.step.one');
Route::post('/form/details', [App\Http\Controllers\Lect\Form\Step1Controller::class, 'postCreateStepOne'])->name('form.create.step.one.post');
Route::get('/form/learning-outcomes', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'createStepTwo'])->name('form.create.step.two');
Route::post('/form/learning-outcomes', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'postCreateStepTwo'])->name('form.create.step.two.post');
...
Model
Step1.php
class Step1 extends Model {
use HasFactory;
public $table = 'forms';
protected $fillable = [
'title',
'code',
'creditvalue',
'mqflevel',
'affectedbatch',
'kulliyyah',
'department',
'synopsis',
'classification',
'prerequisite',
];
}
Step2.php
class Step2 extends Model {
use HasFactory;
public $table = 'proposal_learning_outcome';
public $timestamps = false;
protected $fillable = [
'proposal_id',
'lo_id',
'outcomes',
'bloom_c',
'bloom_a',
'bloom_p',
'ki',
'po',
];
}
Controller
Step1Controller.php
class Step1Controller extends Controller {
public function createStepOne(Request $request) {
return view('form.step1');
}
public function postCreateStepOne(Request $request) {
$validatedData = $request->validate([
'title' => 'required',
'code' => 'required|unique:forms',
'creditvalue' => 'required|numeric',
'mqflevel' => 'required|numeric',
'affectedbatch' => 'required',
'kulliyyah' => 'required',
'department' => 'required',
'synopsis' => 'required',
'classification' => 'required',
'prerequisite' => 'required',
]);
$step1 = new Step1;
$step1->title=$request->input('title');
$step1->code=$request->input('code');
$step1->creditvalue=$request->input('creditvalue');
$step1->mqflevel=$request->input('mqflevel');
$step1->affectedbatch=$request->input('affectedbatch');
$step1->kulliyyah=$request->input('kulliyyah');
$step1->department=$request->input('department');
$step1->synopsis=$request->input('synopsis');
$step1->classification=$request->input('classification');
$step1->prerequisite=$request->input('prerequisite');
$step1->created_by=Auth::user()->username;
$result = $step1->save();
return redirect()->route('form.create.step.two');
}
}
Step2Controller.php
class Step2Controller extends Controller {
public function createStepTwo(Request $request) {
return view('form.step2');
}
public function postCreateStepTwo(Request $request) {
$validatedData = $request->validate([
'proposal_id' => 'required',
'lo_id' => 'required',
'outcomes' => 'required',
'bloom_c' => 'required',
'bloom_a' => 'required',
'bloom_p' => 'required',
'ki' => 'required',
'po' => 'required',
]);
foreach($request->lo_id as $key=>$lo_id) {
$data = new Step2();
$data->proposal_id=$request->input('proposal_id');
$data->lo_id=$lo_id;
$data->outcomes=$request->outcomes[$key];
$data->bloom_c=$request->bloom_c[$key];
$data->bloom_a=$request->bloom_a[$key];
$data->bloom_p=$request->bloom_p[$key];
$data->ki=$request->ki[$key];
$data->po=$request->po[$key];
$data->save();
}
return redirect()->route('form.create.step.three');
}
}
View
step1.blade.php
<form action="{{ route('form.create.step.one.post') }}" method="POST">
#csrf
<div class="card">
Step 1: Basic Info
</div>
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label for="title">Course Title</label>
<input type="text" name="title" class="form-control text-lg" id="title" placeholder="">
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="code">Course Code</label>
<input type="text" name="code" class="form-control text-lg" id="code" placeholder="">
</div>
<div class="form-group">
<label for="creditvalue">Credit Value</label>
<input type="number" name="creditvalue" class="form-control text-lg" id="creditvalue" placeholder="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="mqflevel">MQF Level</label>
<input type="number" name="mqflevel" class="form-control text-lg" id="mqflevel" placeholder="">
</div>
<div class="form-group">
<label for="affectedbatch">Affected Batch</label>
<input type="text" name="affectedbatch" class="form-control text-lg" id="affectedbatch" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<label for="kulliyyah">Centre of Studies</label>
<select type="text" class="form-control text-lg" name="kulliyyah" id="kulliyyah">
<option value="Kulliyyah of Information and Communication Technology">Kulliyyah of Information and Communication Technology</option>
<option value="Kulliyyah of Education">Kulliyyah of Education</option>
<option value="Kulliyyah of Engineering">Kulliyyah of Engineering</option>
<option value="Kulliyyah of Architecture and Environmental Design">Kulliyyah of Architecture and Environmental Design</option>
</select>
</div>
<div class="form-group">
<label for="department">Department/Unit</label>
<select type="text" class="form-control text-lg" name="department" id="department">
<option value="Department of Computer Science">Department of Computer Science</option>
<option value="Department of Information System">Department of Information System</option>
</select>
</div>
<div class="form-group">
<label for="synopsis">Course Synopsis</label>
<textarea type="text" class="form-control text-lg" name="synopsis" rows="5" id="synopsis" placeholder=""></textarea>
</div>
<div class="form-group">
<label for="classification">Course Classification within the Curriculum</label>
<input type="text" class="form-control text-lg" name="classification" id="classification" placeholder="eg: CSC 1305">
</div>
<div class="form-group">
<label for="prerequisite">Prerequisite(s) (if any)</label>
<input type="text" class="form-control text-lg" name="prerequisite" id="prerequisite" placeholder="">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</div>
</form>
step2.blade.php
<form action="{{ route('form.create.step.two.post') }}" method="POST">
#csrf
<div class="card">
Step 2: Course Learning Outcomes</div>
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label for="proposal_id">Proposal ID</label>
<input type="text" class="form-control text-lg" name="proposal_id" id="proposal_id" placeholder="">
</div>
<div class="table-responsive">
<form method="post" id="dynamic_form">
<span id="result"></span>
<table class="table table-bordered" id="user_table">
<thead>
<tr class="table-active">
<th rowspan="2">No.</th>
<th rowspan="2" class="w-50">Outcomes</th>
<th colspan="3" class="w-25">Bloom's Taxonomy</th>
<th rowspan="2">Soft skills (KI)</th>
<th rowspan="2">Programme Outcomes (PO)</th>
<th rowspan="2">Add</th>
</tr>
<tr class="table-active">
<th>C</th>
<th>A</th>
<th>P</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control text-lg" name="lo_id[]"/></td>
<td><textarea class="form-control text-lg" name="outcomes[]"></textarea></td>
<td><input class="form-control text-lg" name="bloom_c[]"/></td>
<td><input class="form-control text-lg" name="bloom_a[]"/></td>
<td><input class="form-control text-lg" name="bloom_p[]"/></td>
<td><input class="form-control text-lg" name="ki[]"/></td>
<td><input class="form-control text-lg" name="po[]"/></td>
<td>Remove</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-6 text-left">
Previous
</div>
<div class="col-md-6 text-right">
<button type="submit" class="btn btn-primary ">Next</button>
</div>
</div>
</div>
</div>
</form>
and the other 5 steps are basically like that.
My current problem is how can I get the proposal_id of the first form (step1) as a reference to the next 6 forms. The proposal_id is used as a foreign key for other tables. The proposal_id is auto-incremented in the table.
The reason I divided them into many tables is that some parts of the form are in table format as shown in step2.blade.php. The image below a reference.
Form example
For now, as you can see in the code, my current solution is to manually input the proposal_id in each form (which is not practical because they would not know the proposal_id in the first place). My current code has no issue. It can be saved into the database as normal.
How can I solve this issue? Or is there another way to fill up this form? Thank you in advance.
You have two solution, the first I see is to pass the proposal_id as a parameter of your route (see below).
Route::get('/form/learning-outcomes{proposal_id}', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'createStepTwo'])->name('form.create.step.two');
The second is to save it in your session variable and you can acess it throught your form
session()->put('proposal_id', $proposal_id)
To get it in your second form use :
session()->get('proposal_id')
Update
Make sure to add this line in your migration file:
$table->id('proposal_id')
where the proposal_id is your primary key autoincrement. By default if you don't put anything as id parameter, it will be id in your column table.
$table->id()//COLUMN TABLE WILL CONTAINT id as name
$table->id('proposal_id')//COLMUN TABLE WILL CONTAINT proposal_id as name
The answer was helpful but not actually what I asked (sorry if my question was not clear). I found the answer to my question.
I wanted to get the proposal_id from the first form. I called the lastest added row in the table like this:
$proposal_id = DB::table('forms')
->select('proposal_id')
->orderBy('proposal_id', 'desc')
->limit(1)
->value('proposal_id');
I added this code in the Step1Controller after
$result = $step1->save();
And then I save it into session like crazy4dev suggested:
$request->session()->put('proposal_id', $proposal_id);
return redirect()->route('form.create.step.two', compact('proposal_id'));
I can access the proposal_id in the Step2Controller with:
$proposal_id = $request->session()->get('proposal_id');
Good afternoon everyone!
In my project I have to create a new user which will be a restaurant directly in the user's registration.
Once registered, I gave the possibility to associate more types of restaurant to the logged in user.
I made already migrations and relations everything is working.
This is what i wrote to permit the logged user(restaurant) to add more typologies.
public function typologyAdd() {
$typologies = Typology::all();
return view('pages.typology-add',compact('typologies'));
}
public function typologyStore(Request $request) {
$data = $request -> all();
$user = Auth::user();
$typologies = Typology::findOrFail($data['typologies']);
$user -> typologies() -> sync($typologies);
return redirect() -> route('home');
}
So this is working only once i register the user.
i want to put this logic when i'm in registration page.
I was trying to modify the RegisterController but i don't know how to do that:
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'indirizzo' => ['required' ,'string','max:255'],
'piva' => ['required','string','min:11','max:11','digits:11','unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'indirizzo' => $data['indirizzo'],
'piva' => $data['piva'],
'password' => Hash::make($data['password']),
]);
}
and to put checkboxes inside the Register.blade.php
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row">
<label for="indirizzo" class="col-md-4 col-form-label text-md-right">{{ __('indirizzo') }}</label>
<div class="col-md-6">
<input id="indirizzo" type="text" class="form-control" name="indirizzo" value="{{ old('indirizzo') }}" maxlength="255" required>
#error('indirizzo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="piva" minlenght="11" maxlength="11" class="col-md-4 col-form-label text-md-right">{{ __('piva') }}</label>
<div class="col-md-6">
<input id="piva" type="text" class="form-control #error('piva') is-invalid #enderror" name="piva" value="{{ old('piva') }}" required>
#error('piva')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
I hope someone will give me some ideas on how to do it, thanks to those who will read and answer
In the RegisterController.php you can get the newly created user by doing the below.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'indirizzo' => $data['indirizzo'],
'piva' => $data['piva'],
'password' => Hash::make($data['password']),
]);
// Do actions on $user and finally return $user
return $user;
}
Add new validations rules if you need any & also if you are doing relation data entry i would suggest to do a SQL transaction based insert. Commit data if no SQL error is thrown. Else rollback the changes to prevent issues.
My framework is Laravel 5.3, How to create array in HTML and insert array to Database in PHP?
For Example $passenger is 2.
In HTML:
#for($i = 1; $i <= $passenger; $i++)
<li id="passenger-adult-{{ $i }}">
<fieldset>
<legend>Passenger</legend>
<div class="row">
<div class="col-md-3 col-md-offset-3">
<div class="form-group">
<label>Name</label>
<input class="form-control" type="text" name="name[]" required/>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Family</label>
<input class="form-control" type="text" name="family[]" required/>
</div>
</div>
</div>
.
.
.
</fieldset>
</li>
#endfor
After send passenger data Array is:
Array
(
[_method] => PATCH
[_token] => OwNvaXUvoGAKL25UN85GBiV7pN5I2ILEXw7vZrMa
[name] => Array
(
[0] => amir
[1] => ali
)
[family] => Array
(
[0] => hesari
[1] => ahmadi
)
.
.
.
)
But! I need create array in this case, for insert to database:
Array
(
[_method] => PATCH
[_token] => OwNvaXUvoGAKL25UN85GBiV7pN5I2ILEXw7vZrMa
[passenger] => Array
(
[name] => amir
[family] => hesari
.
.
.
)
[passenger] => Array
(
[name] => ali
[family] => ahmadi
.
.
.
)
)
change this code
<input class="form-control" type="text" name="name[]" required/>
to
<input class="form-control" type="text" name="passenger[{{$i}}][name]" required/>
change this
<input class="form-control" type="text" name="family[]" required/>
to
<input class="form-control" type="text" name="passenger[{{$i}}][family]" required/>
I have 2 input arrays one is checkbox and and another one is textbox
which is my view file
<div class="form-group">
<label class="col-lg-2 control-label">Fee Types</label>
<div class="col-lg-8">
<div class="checkbox">
<?php foreach($types as $key=>$value){?>
<label>
<input type="checkbox" value="<?php echo $value['id'] ?>" name="type_id[]" />
<span class="text"><?php echo $value['name'] ?></span>
</label>
<input type="text" class="form-control" name="amount[]" />
<?php } ?>
</div>
</div>
</div>
which is my controller
$data=array(
'id'=>$this->input->post('id'),
'amount'=>$this->input->post('amount'),
'type_id'=>$this->input->post('type_id'),
'created_date'=>date('Y-m-d'),
);
$this->user->details($data);
could anyone tell me how to insert those two arrays as multiple records
$checkboxes = $this->input->post('type_id[]');
$amounts= $this->input->post('amount[]');
for ($i = 0; $i < count($amounts); $i++) {
$data = array(
'id'=> $yourIdPostField,
'amount'=>$amounts[$i],
'type_id'=> $checkboxes[$i],
'created_date'=>date('Y-m-d'),
);
$this->user->details($data);
}
This is simple way... but maybe your problem is no checkbox post data becouse not checked, if you want that problem then add increment number to your form ...
<div class="form-group">
<label class="col-lg-2 control-label">Fee Types</label>
<div class="col-lg-8">
<div class="checkbox">
<?php foreach($types as $key=>$value){?>
<label>
<input type="checkbox" value="<?php echo $value['id'] ?>" name="type_id[$key]" />
<span class="text"><?php echo $value['name'] ?></span>
</label>
<input type="text" class="form-control" name="amount[<?php echo $key ?>]" />
<?php } ?>
</div>
</div>
</div>
$checkboxes = $this->input->post('type_id[]');
$amounts= $this->input->post('amount[]');
$example1 = implode(" ",$checkboxes);
$example2 = implode(" ",$amounts);
Please try this. I hope your problem will be solve.
$checkboxes, $amounts this variables is array so these variable value could not store in your database. So please convert array to string.
Thanks
i am using a CakePHP form Creator
echo $form->input($r['Attribute']['label'], array('id'=>$r['Attribute']['id'],'name'=>$r['Attribute']['label'],'type'=>'text','style' => 'width:30px'));
echo $form->input($r['Attribute']['label'], array('label'=>false,'div' => false,'id'=>$r['Attribute']['id'].'-','name'=>$r['Attribute']['label'],'type'=>'text','style' => 'width:30px'));
which creates a Input Box and the generated Html is like
<div class="input text">
<label for="6">Mobile Number</label>
<input type="text" value="" style="width: 30px;" id="6" name="Mobile Number"/>
</div>
<input type="text" value="" style="width: 30px;" id="6-" name="Mobile Number"/>
But i need this second input Text Box to appear inside the above Div ..Please suggest me.
<div class="input text">
<?php
echo $form->input($r['Attribute']['label'], array('id'=>$r['Attribute']['id'],'name'=>$r['Attribute']['label'],'type'=>'text','style' => 'width:30px', 'div' => false));
echo $form->input($r['Attribute']['label'], array('label'=>false,'div' => false,'id'=>$r['Attribute']['id'].'-','name'=>$r['Attribute']['label'],'type'=>'text','style' => 'width:30px'));
?>
</div>
Note that I've added 'div' => false to the first input too.
But wouldn't this give you two inputs with the same name?