Laravel add/remove input fields update values problem - laravel

I use add/remove input fields with jquery and have problem when I want to update the values.
In the store() method foreach loop fetches all input fields that I added, while in the update() method foreach loop fetched only first input.
How can I fix this?
I have two tables "attributes(id,name)" and "attribute_option(id,attribute_id,attribute_value").
In edit.balde.php
<script type="text/javascript">
$("#add").click(function(){
addRow();
}}
function addRow(){
$("optionsTable").append('<tr><td><input type="text" name="value[]" class="form-control"</td><td><button type="button" class="remove-tr">Remove</button></td></tr>);
};
$(document).on('click','.remove-tr', function(){
$(this).parents('tr).remove();
});
</script>
<button type="button" id="add">Add row</button>
#foreach($attribute_options as $key=>$option)
<tr>
<td>
<input type="hidden" name="option_id[]" value="{{ $option->id }}">
<input type="text" name="value[]" value="{{ $option->attribute_value }}">
</td>
<td>
<button type="button" class="remove-tr">Remove</button>
</td>
</tr>
#endforeach
in my controller action update()
if($request->has('value)){
$options = $request->value;
$option_id = $request->option_id;
foreach($options as $value){
AttributeOption::where('id','=',$option_id)->update(array(
'attribute_value' => $value
));
}
}

Because $option_id is also an array and therefore also must be read as an array:
if($request->has('value')){
$options = $request->value;
$option_id = $request->option_id;
foreach($options as $key => $value){
AttributeOption::where('id','=',$option_id[$key])->update(array(
'attribute_value' => $value
));
}
}

Related

How to pass the date within an array to the database in laravel

I have made the following migration in Laravel:
public function up()
{
Schema::create('attendances', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('student_id');
$table->date('att_date')();
$table->string('status');
$table->timestamps();
});
}
My Form in Blade look like this
<form method="post" action="{{url('att-sumbit')}}" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<strong>Date : </strong>
<input class="date form-control" type="text" id="datepicker" name="att_date[]">
</div>
</div>
<div class="mb-3">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Level</th>
<th>Status</th>
</tr>
#foreach($students_att as $student)
<tr>
<td>{{$student -> id}}</td>
<td>{{$student -> name}}</td>
<td>{{$student -> level}}</td>
<td>
<input type="hidden" id="custId" name="student_id[]" value="{{$student -> id}}">
</td>
<td>
<select name="status[]">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</td>
</tr>
#endforeach
</table>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
<script type="text/javascript">
$('#datepicker').datepicker({
autoclose: true,
format: 'yyyy-mm-dd'
});
</script>
and I have made my Controller like this:
public function sumbit(Request $request)
{
/* $submit = new Attendance;
$submit->student_id = $request->get('student_id');
// $submit->att_date = $request->get('att_date');
// $submit->status = $request->get('status');
$submit->save();
return redirect('att'); */
$studentID = $request->input('student_id', []);
$studentDate = $request->input('att_date', []);
$studentStatus = $request->input('status', []);
$students = [];
foreach ($studentID as $index => $student) {
$students[] = [
"student_id" => $studentID[$index],
"att_date" => $studentDate[$index],
"status" => $studentStatus[$index],
];
}
$create = Attendance::insert($students);
}
so I want when i submit my form, it must be record the same date that i used by date picker to every input that show in the following image to my database
but when i did this procedure, i got this error (ErrorException
Undefined offset: 1) the error in this line in my controller line
"att_date" => $studentDate[$index],
How can Ii fix this error please help
"att_date" => $studentDate[$index], should be "att_date" => $studentDate[0]. You only have one date in that form.
Lets something more simple.
#foreach($students_att as $student)
<tr>
<td>{{$student -> id}}</td>
<td>{{$student -> name}}</td>
<td>{{$student -> level}}</td>
<td>
<input type="hidden" id="custId" name="student[student_id][]" value="{{ $student->id }}">
</td>
<td>
<select name="student[status][]">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</td>
</tr>
#endforeach
Controller :
$students = $request->student;
foreach($students as $key => $value) {
$students[$key]['att_date'] = $request->att_date[0];
}
$create = Attendance::insert($students);
Change the migration from date to timestamp, also use Carbon::parse before inserting it to the database.
Carbon::parse($datevariable)

search by multiple values using checkbox in laravel

I have job_sector table in which sector_id and job_id fields are there. I just want to search job_id by the sectors which I have selected through checkbox. One may select multiple sectors.
My model :
public function scopeSelectedOptions($query, $input = [])
{
if(!empty($input)) {
if(array_key_exists('sector_id', $input)) {
$query->whereHas('sector_id', function($q) use ($input) {
return $q->whereIn('sector_id', $input['sector_id']);
});
}
}
return $query;
}
Controller :
public function jobsFilter(Request $request)
{
$jobs = JobSector::SelectedOptions(request()->all())->get();
return view('front.pages.job.jobfilter')->with(['title'=>'Job Filter', 'jobs' => $jobs]);
}
Form from where I am selecting multiple sectors :
<form action="{{ route('job.jobfilter') }}" method="GET" class="mb-4">
{{csrf_field()}}
#foreach(get_sectors() as $k=>$s)
<input type="checkbox" name="input[]" value="{{ $k }}">{{ $k }}<br>
#endforeach
<input type="submit" value="Search" />
</form>
Query showing the output :
#foreach($jobs as $c)
{{ $c->job_id }} <br>
#endforeach
It shows me all the job_id in the table.
Please help me out,
You are giving the wrong array to your scope
it would look like this :
['input' => ['12' => true]]
try this
<form action="{{ route('job.jobfilter') }}" method="GET" class="mb-4">
{{csrf_field()}}
#foreach(get_sectors() as $k=>$s)
<input type="checkbox" name="sector_id[{{ $k }}]">{{ $k }}<br>
#endforeach
<input type="submit" value="Search" />
</form>
public function jobsFilter(Request $request)
{
$jobs = JobSector::whereIn('sector_id', array_keys(request()->sector_id))->get();
return view('front.pages.job.jobfilter')->with(['title'=>'Job Filter', 'jobs' => $jobs]);
}
(I just ignore your scope to be more readable)

Input Modal using Bulma cant parsing id Laravel

So iam using bulma for my modal input and i have problem in my input always get 404 . and this problem is this id cant stored on this form . you can see this form like this and i dont know where my fault
1.Table // #update , this problem on here this {{i->id}} cant send into js code , whats wrong ??
#foreach ($data as $i)
<tr>
<td>{{ $i->turunan_anak->uraian}}</td>
<td>16</td>
<td>46</td>
<td>{{$i->kode_rekening}}</td>
<td>{{$i->uraian}}</td>
#if(empty($i->user_id))
<td>belum dipilih</td>
#else()
<td> $i->users->nama_unit</td>
#endif
<td>
<a class = "button is-danger modal-button" id="lanuchModal"
data-id="{{$i->id}}"
data-user_id="{{$i->user_id}}"
data-target="#modal"
>Pilih Pelaksana</a>
</td>
#endforeach
2.Modal
<form action="{{route('store_id'),'test'}} " method="post">
#csrf
{{method_field('patch')}}
<div id="modal" class="modal">
<div class="modal-background"></div>
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title">Pilih Pelaksana</p>
<button class="delete" id="modal-close" aria-label="close"></button>
</header>
<section class="modal-card-body">
<div class="field">
<div class="control">
<div class="select is-medium is-danger">
<select id="user_id" name="user_id">
#foreach($pelaksana as $id => $nama )
<option value="{{ $id }}">{{ $nama }}</option>
#endforeach
</select>
</div>
<input type="hidden" name="id" id="id" value="">
</div>
</div>
</section>
<footer class="modal-card-foot">
<button type="submit" class="button is-success">Save changes</button>
</footer>
</div>
</div>
</form>
My Js for modal # this id not received data-id , and its the problem
<script>
$('.modal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var id = button.data('id')
var user_id = button.data('user_id')
var modal = $(this)
modal.find('.modal-card-body #id').val(id);
modal.find('.modal-card-body #user_id').val(user_id);
})
</script>
and last its my die dump
array:4 [▼
"_token" => "KV5anuTdRXWt3RKHtFMzgud6DN69PzXQX0Pj9ire"
"_method" => "patch"
"user_id" => "3"
"id" => null
]
this id always null i dont know what happen , anyone have solution ?
#update my controller
public function index()
{
$pelaksana = User::where('roles_id' ,2)->pluck('nama_unit', 'id');
$data = TurunanBelanja::all();
// dd($pelaksana);
return view('admin.dashboard',['data'=>$data , 'pelaksana' => $pelaksana]);
}
public function store_id(Request $request)
{
$data = TurunanBelanja::findOrFail($request->id);
$data->user_id = $request->user_id;
$data->update();
return back()->with('success', 'Sukses Update Data');
}
this controller is work normaaly , i try to set value id=1 . and this input is work normmaly

I got this error "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type

When i try to insert data into my table this error occurs
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\Portal\vendor\laravel\framew...
view
<form method="post" action="{{ route('notice.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="Select Group to Post Notice">Select Group to Post Notice </label>
<select class="bg-white text-danger form-control " name='GroupID[]' multiple>
#foreach ($users as $user)
<option value="{{ $user->GroupID }}">{{ $user->GroupID }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="Enter Notice">Enter Notice</label>
<input class="bg-white text-danger p-2 form-control form-control-sm" type="text" name="Notice" placeholder="Enter Notice">
</div>
<input class="btn btn-danger btn-lg px-5" type="submit" name="submit">
</form>
controller
public function store(Request $request)
{
$member = $request->input('GroupID');
foreach($member as $value) {
$storeInfo = new notice();
$storeInfo->GroupID = $request->input('GroupID');
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}
I would imagine the reason you're getting this error is because of:
$storeInfo->GroupID = $request->input('GroupID');
$request->input('GroupID') will return an array (name='GroupID[]') and not an individual id.
Since you're already looping through the group ids you can instead use the value for the GroupId:
public function store(Request $request)
{
foreach ($request->input('GroupID') as $groupId) {
$storeInfo = new notice();
$storeInfo->GroupID = $groupId; //<--here
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('notice');
}
try changing controller logic
public function store(Request $request)
{
//
$member=$request->input('GroupID');
foreach($member as $value){
$storeInfo = new notice();
$storeInfo->GroupID = $value;
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}

How to add additional tags to csv import data at time of import

Using a text input field I need to add tags to the records being imported via CSV import module. In the controller, I am automatically adding user id, team id, and timestamp to all imported records and now I need to add user-defined tags to all records at the time of import.
What do in need in my controller to achieve this functionality?
<?php
`namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use SpreadsheetReader;
use Illuminate\Support\Facades\File;
class CsvImportController extends Controller
{
public function parse(Request $request)
{
$file = $request->file('csv_file');
$request->validate([
'csv_file' => 'mimes:csv,txt',
]);
$path = $file->path();
$hasHeader = $request->input('header', false) ? true : false;
$reader = new SpreadsheetReader($path);
$headers = $reader->current();
$lines = [];
$lines[] = $reader->next();
$lines[] = $reader->next();
$filename = str_random(10) . '.csv';
$file->storeAs('csv_import', $filename);
$modelName = $request->input('model', false);
$fullModelName = "App\\" . $modelName;
$model = new $fullModelName();
$fillables = $model->getFillable();
$redirect = url()->previous();
return view('csvImport.parse_import',
compact('headers', 'filename', 'fillables', 'hasHeader', 'modelName', 'lines', 'redirect'));
}
public function process(Request $request)
{
$filename = $request->input('filename', false);
$path = storage_path('app/csv_import/' . $filename);
$hasHeader = $request->input('hasHeader', false);
$fields = $request->input('fields', false);
$fields = array_flip(array_filter($fields));
$modelName = $request->input('modelName', false);
$model = "App\\" . $modelName;
$reader = new SpreadsheetReader($path);
$insert = [];
foreach ($reader as $key => $row) {
if ($hasHeader && $key == 0) {
continue;
}
$tmp = [];
foreach ($fields as $header => $k) {
$tmp[$header] = $row[$k];
}
if (auth()->user()->team_id) {
$tmp['created_by_id'] = auth()->user()->id;
$tmp['created_by_team_id'] = auth()->user()->team_id;
$tmp['created_at'] = now();
}
$insert[] = $tmp;
}
$for_insert = array_chunk($insert, 100);
foreach ($for_insert as $insert_item) {
$model::insert($insert_item);
}
$rows = count($insert);
$table = str_plural($modelName);
File::delete($path);
$redirect = $request->input('redirect', false);
return redirect()->to($redirect)->with('message', trans('global.app_imported_rows_to_table',
['rows' => $rows, 'table' => $table]));
}
My View:
<div class='row'>
<div class='col-md-12'>
<div class="panel panel-default">
<div class="panel-heading">
#lang('global.app_csvImport')
</div>
<div class="panel-body table-responsive">
<form class="form-horizontal" method="POST" action="{{ route('admin.csv_process') }}">
{{ csrf_field() }}
<input type="hidden" name="filename" value="{{ $filename }}"/>
<input type="hidden" name="hasHeader" value="{{ $hasHeader }}"/>
<input type="hidden" name="modelName" value="{{ $modelName }}"/>
<input type="hidden" name="redirect" value="{{ $redirect }}"/>
<table class="table">
#if (isset($headers))
<tr>
#foreach ($headers as $field)
<th>{{ $field }}</th>
#endforeach
</tr>
#endif
#if($lines)
#foreach ($lines as $line)
<tr>
#foreach ($line as $field)
<td>{{ $field }}</td>
#endforeach
</tr>
#endforeach
#endif
<tr>
#foreach ($headers as $key => $header)
<td>
<select name="fields[{{ $key }}]">
<option value=''>Please select</option>
#foreach ($fillables as $k => $fillable)
<option value="{{ $fillable }}"
#if (strtolower($header) === strtolower($fillable)) selected #endif>{{ $fillable }}</option>
#endforeach
</select>
</td>
#endforeach
</tr>
</table>
<button type="submit" class="btn btn-primary" id="btn-import">
#lang('global.app_import_data')
</button>
<button type="submit" class="btn btn-primary" id="btn-import2">
#lang('global.app_import_data')
</button>
</form>
</div>
</div>
</div>

Resources