Laravel - How to validate fields from another tables in Request Rules - laravel

Using Laravel-5.8, I am trying to delevop a web application.I have two tables: goals and goal_details. Goal is the main model class.
Using Rules and Request in Laravel:
public function rules()
{
return [
'goal_title' => 'required|min:5|max:100',
'goal_type_id' => 'required',
'weighted_score' => 'required|numeric|min:0|max:500',
'start_date' => 'required',
'end_date' => 'required|after_or_equal:start_date',
'kpi_description' => 'required',
'activity' => 'required',
];
}
goals: customer_id, goal_title, weighted_score, start_date, end_date
goal_details: goal_type_id, kpi_description
public function create()
{
$userCompany = Auth::user()->company_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$goaltypes = GoalType::where('company_id', $userCompany)->get();
$categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities);
}
public function store(StoreGoalRequest $request)
{
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new GoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->save();
}
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}
create.blade.php
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-secondary">
<!-- /.card-header -->
<!-- form start -->
<form method="POST" action="{{route('goals.store')}}">
#csrf
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option disabled="disabled" value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Activity<span style="color:red;">*</span></th>
<th scope="col">KPI Description<span style="color:red;">*</span></th>
<th scope="col">Attachment</th>
<th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi" ></td>
<td>
<div class="custom-file">
<input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="exampleInputFile">Choose file</label>
</div>
</td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Weight:</label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Start Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="start_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> End Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="end_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_goals.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
javascript
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
var isHod = {{ Auth::user()->is_hod == 0 ? 0 : 1 }};
var numRows = $('.activity').length
if (isHod || (!isHod && numRows<3)) {
addRow();
}
});
function addRow() {
var addRow = '<tr>\n' +
' <td><input type="text" name="activity[]" class="form-control activity" ></td>\n' +
' <td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>\n' +
' <td><div class="custom-file"><input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile"><label class="custom-file-label" for="exampleInputFile">Choose file</label></div></td>\n' +
' <td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
function addRemoveListener() {
$('.remove').on('click', function () {
var l =$('tbody tr').length;
if(l==1){
alert('you cant delete last one')
}else{
$(this).parent().parent().remove();
}
});
}
</script>
When I submitted, I observed that the fields from goal_details: goal_type_id, kpi_description are not validated as required. It allows null. But all fields in goals are validated.
How do I resolve this?
Thank you.

Check if it can solve your "kpi_description" validation problem :
public function rules()
{
return [
'goal_title' => 'required|min:5|max:100',
'goal_type_id' => 'required',
'weighted_score' => 'required|numeric|min:0|max:500',
'start_date' => 'required',
'end_date' => 'required|after_or_equal:start_date',
'kpi_description' => 'required|array',
'kpi_description.*' => 'required',
'activity' => 'required',
];
}

after defining rules you have to call "validated" method as needed.
try this :
public function store(StoreGoalRequest $request)
{
$validated = $request->validated();
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new GoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->save();
}
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}

Related

My data is not saving in the database.I could not do it in the controller part, how can I do something

When you save, other input data comes to the database, while the data from TourDay does not come. The relationship is established in the Migration and Model section. I could not do it in the controller part, how can I do something..
my blade:
<div class="row">
<div class="col-lg-12">
<div class="card card-custom card-stretch ">
<div class="card-header">
<h3 class="card-title">GRUP OLUŞTUR</h3>
</div>
<form method="post" class="form" id="dynamic_form" enctype="multipart/form-data">
#csrf
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li><b>{{ $error }}</b></li>
#endforeach
</ul>
</div>
#endif
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Otel Seçimi:</strong></label>
<div class="col-lg-3">
<select class="form-control select2 " id="kt_select2_5" name="hotel[]" multiple="" tabindex="-1" aria-hidden="true">
<optgroup label="Oteller">
#foreach($hotels as $hotel)
<option value="{{$hotel->id}}" >{{$hotel->name}}</option>
#endforeach
</optgroup>
</select>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Grup Kodu :</strong></label>
<div class="col-lg-3">
<div class="input-group input-group">
<div class="input-group-prepend"><span class="input-group-text" >Grup-Kodu:</span></div>
<input type="text" class="form-control form-control-solid" placeholder="TourKey-123-456" name="code" value="{{old('code')}}">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Rehber Ata:</strong></label>
<div class="col-lg-3">
<select class="form-control form-control-solid" id="exampleSelectd" name="guide_id">
#foreach($guides as $guide)
<option value="{{ $guide->id }}" #if(old('guide_id')===$guide->id) selected #endif>{{$guide->full_name}}</option>
#endforeach
</select>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Müşteri Seçimi:</strong></label>
<div class="col-lg-3">
<select class="form-control select2 " id="kt_select2_3" name="user[]" multiple="" data-select2-id="kt_select2_3" tabindex="-1" aria-hidden="true">
<optgroup label="Müşteriler" >
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->full_name}}</option>
#endforeach
</optgroup>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Başlangıç Tarihi:</strong></label>
<div class="col-lg-3">
<div class="input-group date">
<input type="text" class="form-control" id="kt_datepicker_2" name="started_at" value="{{old('started_at')}}" placeholder="Başlangıç Tarihi seçin.">
<div class="input-group-append">
<span class="input-group-text">
<i class="la la-calendar-check-o"></i>
</span>
</div>
</div>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Bitiş Tarihi:</strong></label>
<div class="col-lg-3">
<div class="input-group date">
<input type="text" class="form-control" id="kt_datepicker_2" name="finished_at" value="{{old('finished_at')}}" placeholder="Başlangıç Tarihi seçin.">
<div class="input-group-append">
<span class="input-group-text">
<i class="la la-calendar-check-o"></i>
</span>
</div>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label text-lg-right"><strong>Aktivite olacak mı? (Opsiyonel)</strong></label>
<div class="col-lg-3 d-flex justify-content-center">
<div class="radio-inline">
<label class="radio radio-lg">
<input type="radio" onclick="aktivite(0)" #if(old('activity')) checked="checked" #endif name="radios3_1" class="form-control"/>
<span></span>
Evet
</label>
<label class="radio radio-lg">
<input type="radio" onclick="aktivite(1)" #if(!old('activity')) style='display:none' #endif name="radios3_1" class="form-control"/>
<span></span>
Hayır
</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right" for="kt_select2_2"></label>
<div class="col-lg-4">
<div class="form-group" id="myAktivite">
<label for="kt_select2_2"><strong>Aktivite Seçimi Yapın:</strong></label>
<select class="form-control select2 " id="kt_select2_2" name="activity[]" multiple="" data-select2-id="kt_select2_2" tabindex="-1" aria-hidden="true">
<optgroup label="Aktiviteler">
#foreach($activities as $activity)
<option value="{{$activity->id}}">{{$activity->title}}</option>
#endforeach
</optgroup>
</select>
</div>
</div>
</div>
</div>
<div class="separator separator-dashed my-8"></div>
<div class="row col-lg-6">
<div class="col-lg-1"></div>
<h4 class="title col-lg-4">TUR EKLE</h4>
</div>
<div class="separator separator-dashed my-8"></div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Tur Başlığı:</strong></label>
<div class="col-lg-3">
<input type="text" name="tour_title" value="{{old('tour_title')}}" class="form-control form-control-solid" placeholder="Lütfen tur başlığı giriniz"/>
</div>
<label class="col-lg-2 col-form-label text-lg-right"></label>
<div class="col-lg-3">
<div class="custom-file form-group">
<input type="file" class="custom-file-input form-control-solid" id="customFile" multiple>
<label class="custom-file-label" for="customFile">Resim Yükle</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right" for="editable"><strong>İçerik Detay</strong></label>
<div class="col-lg-8">
<textarea id="editable" class="form-control" placeholder="" name="tour_description" value="{{old('tour_description')}}">
</textarea>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-8">
<h3 align="center">Tur Detayı (Gün gün yapılacakları ekleyin):</h3>
<br />
<div class="table-responsive">
<span id="result"></span>
<table class="table table-bordered table-striped" id="user_table">
<thead>
<tr>
<th width="22%">Başlık(Kaçıncı Gün)</th>
<th width="22%">İçerik</th>
<th width="22%">Öğle Yemeği</th>
<th width="22%">Akşam Yemeği</th>
<th width="12%">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div class="card-footer">
<div class="row ">
<div class="col-lg-10 d-flex justify-content-end">
<button type="submit" name="save" id="save" class="btn btn-success mr-2">Kaydet</button>
<button type="reset" class="btn btn-secondary">İptal Et</button>
</div>
<div class="col-lg-2"></div>
</div>
</div>
</form>
</div>
</div>
my script:
<script>
$(document).ready(function(){
var count = 1;
dynamic_field(count);
function dynamic_field(number)
{
html = '<tr>';
html += '<td><input type="text" name="title[]" class="form-control" /></td>';
html += '<td><input type="text" name="description[]" class="form-control" /></td>';
html += '<td><input type="text" name="lunch[]" class="form-control" /></td>';
html += '<td><input type="text" name="dinner[]" class="form-control" /></td>';
if(number > 1)
{
html += '<td><button type="button" name="remove" id="" class="btn btn-light-danger remove"><i class="la la-trash-o">Sil</button></td></tr>';
$('tbody').append(html);
}
else
{
html += '<td><button type="button" name="add" id="add" class="btn btn-light-success"><i class="la la-plus"> Ekle' +
'' +
'</button></td></tr>';
$('tbody').html(html);
}
}
$(document).on('click', '#add', function(){
count++;
dynamic_field(count);
});
$(document).on('click', '.remove', function(){
count--;
$(this).closest("tr").remove();
});
$('#dynamic_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'{{ route("groups.store") }}',
method:'post',
data:$(this).serialize(),
dataType:'json',
beforeSend:function(){
$('#save').attr('disabled','disabled');
},
success:function(data)
{
if(data.error)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<p>'+data.error[count]+'</p>';
}
$('#result').html('<div class="alert alert-danger">'+error_html+'</div>');
}
else
{
dynamic_field(1);
$('#result').html('<div class="alert alert-success">'+data.success+'</div>');
}
$('#save').attr('disabled', false);
}
})
});
});
</script>
my Group Model:
protected $fillable = [
'guide_id','code','started_at','finished_at','tour_title','tour_description'
];
public function tourDays(){
return $this ->hasMany('App\Models\TourDay');
}
my TourDay Model:
protected $fillable = [
'group_id','title', 'description','lunch','dinner'
];
public function group(){
return $this ->belongsTo('App\Models\Group');
}
my GroupController:
public function store(Request $request)
{
$data=$request->only('guide_id','code','started_at','finished_at','tour_title','tour_description');
$group=Group::create($data);
if($request->ajax())
{
$rules = array(
'title.*' => 'required',
'description.*' => 'required',
'lunch.*'=>'required',
'dinner.*'=>'required',
);
$error =Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$title = $request->title;
$description = $request->description;
$lunch = $request->lunch;
$dinner = $request->dinner;
for($count = 0; $count < count($title); $count++)
{
$tourDay = new TourDay([
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count]]);
$group->tourDays()->saveMany($tourDay);
$data = array(
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count]
);
$insert_data[] = $data;
}
TourDay::insert($insert_data);
}
return redirect()
->route('groups.index')->withMessage('Rehber başarıyla oluşturuldu!');
}
In your store method put this codes:
public function store(Request $request) {
$data=$request->only('guide_id', 'code', 'started_at', 'finished_at','tour_title', 'tour_description');
$group=Group::create($data);
if($request->ajax())
{
$rules = array(
'title.*' => 'required',
'description.*' => 'required',
'lunch.*'=>'required',
'dinner.*'=>'required',
);
$error =Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$title = $request->title;
$description = $request->description;
$lunch = $request->lunch;
$dinner = $request->dinner;
for($count = 0; $count < count($title); $count++)
{
$tourDay = [
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count],
'group_id' => $group->id
];
TourDay::create($tourDay);
}
}
return redirect()
->route('groups.index')->withMessage('Rehber başarıyla oluşturuldu!');
}

How to retain the values in input fields when form submit fails in Laravel

I have this code in Laravel-5.8. There are two models:
class HrLeaveType extends Model
{
protected $table = 'hr_leave_types';
protected $primaryKey = 'id';
protected $fillable = [
'leave_type_name',
'leave_type_code',
'description',
];
public function leavetypedetail()
{
return $this->hasMany('App\Models\Hr\HrLeaveTypeDetail');
}
}
class HrLeaveTypeDetail extends Model
{
protected $table = 'hr_leave_type_details';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'leave_type_id',
'company_id',
'employee_type_id',
'no_of_days',
];
protected $casts = [
'data' => 'array',
];
public function leavetype()
{
return $this->belongsTo('App\Models\Hr\HrLeaveType', 'leave_type_id', 'id');
}
public function employeetype()
{
return $this->belongsTo('App\Models\Hr\HrEmployeeType', 'employee_type_id', 'id' );
}
}
Request Rules
public function rules()
{
return [
'leave_type_name' => [
'required',
'string',
'min:3',
'max:80',
Rule::unique('hr_leave_types')->where(function ($query) {
return $query->where('leave_type_name', $this->leave_type_name)
->where('company_id', $this->company_id);
})
],
'leave_type_code' => [
'nullable',
'string',
'max:10',
Rule::unique('hr_leave_types')->where(function ($query) {
return $query->where('leave_type_code', $this->leave_type_code)
->where('company_id', $this->company_id);
})
],
'no_of_days' => 'required|array',
'no_of_days.*' => [
'required',
'numeric',
'max:120'
],
'employee_type_id' => 'required|array',
'employee_type_id.*' => [
'required',
],
];
}
}
Controller
public function create()
{
$userCompany = Auth::user()->company_id;
$employeetypes = HrEmployeeType::where('company_id', $userCompany)->get();
$leavetype = new HrLeaveType();
return view('leave.leave_types.create')
->with('leavetype', $leavetype)
->with('employeetypes', $employeetypes);
}
public function store(StoreLeaveTypeRequest $request)
{
$userCompany = Auth::user()->company_id;
$leavetype = new HrLeaveType();
$leavetype->leave_type_name = $request->leave_type_name;
$leavetype->leave_type_code = $request->leave_type_code;
$leavetype->description = $request->description;
$leavetype->save();
foreach ($request->employee_type_id as $key => $employee_type_id){
$insert_array = [
'no_of_days' => $request->no_of_days[$key],
'employee_type_id' => $request->employee_type_id[$key],
'leave_type_id' => $leavetype->id,
];
HrLeaveTypeDetail::create($insert_array );
}
Session::flash('success', 'Leave Type is created successfully');
return redirect()->route('leave.leave_types.index');
}
}
LeaveTypeDetail is dynamically created
create.blade
#if (Session::has('error'))
<div class="alert alert-warning" align="left">
×
<strong>!</strong> {{Session::get('error')}}
</div>
#endif
<br>
#include('partials._messages')
<form action="{{route('leave.leave_types.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Name:<span style="color:red;">*</span></label>
<input type="text" name="leave_type_name" value="{{ old('leave_type_name', $leavetype->leave_type_name) }}" placeholder="Enter leave type name" class="form-control #error('leave_type_name') is-invalid #enderror">
#error('leave_type_name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Code:</label>
<input type="text" name="leave_type_code" value="{{ old('leave_type_code', $leavetype->leave_type_code) }}" placeholder="Enter leave typecode" class="form-control #error('leave_type_code') is-invalid #enderror">
#error('leave_type_code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Description</label>
<textarea rows="2" name="description" class="form-control #error('description') is-invalid #enderror" value="{{old('description',$leavetype->description)}}" placeholder="Enter Description here ...">{{old('description',$leavetype->description)}}</textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Employee Type<span style="color:red;">*</span></th>
<th scope="col">Leave Days<span style="color:red;">*</span></th>
<th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td width="60%">
<option value="0" selected="true" disabled="true">Select Employee Type</option>
#if($employeetypes->count() > 0 )
#foreach($employeetypes as $employeetype)
<option name="employee_type_id[]" value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>
#endforeach
#endif
</select>
</td>
<td width="35%"><input type="text" name="no_of_days[]" placeholder="Enter leave days here" class="form-control no_of_days" max="120"></td>
<td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('leave.leave_types.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
addRow();
});
function addRow() {
var addRow = '<tr>\n' +
' <td width="60%"><select class="form-control select2bs4" data-placeholder="Choose Employee Type" tabindex="1" name="employee_type_id[]">\n' +
' <option value="0" selected="true" disabled="true">Select Employee Type</option>\n' +
' #if($employeetypes->count() > 0 )\n' +
' #foreach($employeetypes as $employeetype)\n' +
' <option value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td width="35%"><input type="text" name="no_of_days[]" placeholder="Enter leave days here" class="form-control no_of_days" max="120"></td>\n' +
' <td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
</script>
One leave type has many leave type details. For the controller and view, I have dynamic form input.
leave_type_details are arrays.
When user submits, if action fails all the fields should retail their values. This happens to only leave_type, but leave_type_details fields did not retain their values. It clears off.
How do I achieve this?
Thanks
in blade :
#if(old('input_name'))
#foreach(old('input_name') as $key => $value)
<your_html>{{old("input_name.{$key}"}}</your_html>
#endforeach
#endif

Laravel - Dynamic input form duplicates record during update

I am trying to create Dynamic input form array using Laravel-5.8
I have these two models:
class HrLeaveType extends Model
{
protected $table = 'hr_leave_types';
protected $fillable = [
'company_id',
'leave_type_name',
'no_of_days',
'leave_type_code',
];
}
class HrLeaveTypeDetail extends Model
{
protected $table = 'hr_leave_type_details';
protected $fillable = [
'id',
'leave_type_id',
'company_id',
'employment_type_code',
'no_of_days',
];
public function leavetype()
{
return $this->belongsTo('App\Models\Hr\HrLeaveType', 'leave_type_id', 'id');
}
public function employmenttype()
{
return $this->belongsTo('App\Models\Hr\HrEmploymentType', 'employment_type_code', 'employment_type_code' );
}
}
Request Rules:
class UpdateLeaveTypeRequest extends FormRequest
{
public function rules()
{
'leave_type_name' =>
[
'required',
Rule::unique('hr_leave_types')->where(function ($query) {
return $query
->where('leave_type_name', 1)
->where('company_id', 1);
})->ignore($this->leave_type)
],
'leave_type_code' => [
'nullable',
'string',
'max:10',
],
'no_of_days' => 'required|array',
'no_of_days.*' => [
'required',
'numeric',
'max:120'
],
'employment_type_code' => 'required|array',
'employment_type_code.*' => [
'required',
],
];
}
}
And then the Controller:
public function edit($id)
{
$userCompany = Auth::user()->company_id;
$leavetype = HrLeaveType::findOrFail($id);
$employmenttypes = HrEmploymentType::where('company_id', $userCompany)->get();
$leavetypedetails = HrLeaveTypeDetail::where('leave_type_id', $id)->get();
return view('leave.leave_types.edit')
->with('leavetype', $leavetype)
->with('leavetypedetails', $leavetypedetails)
->with('employmenttypes', $employmenttypes);
}
public function update(UpdateLeaveTypeRequest $request, $id)
{
DB::beginTransaction();
try {
$leavetype = HrLeaveType::findOrFail($id);
$leavetype = new HrLeaveType();
$leavetype->leave_type_name = $request->leave_type_name;
$leavetype->leave_type_code = $request->leave_type_code;
$leavetype->description = $request->description;
$leavetype->save();
HrLeaveTypeDetail::where('leave_type_id', $id)->delete();
foreach ( $request->employment_type_code as $key => $employment_type_code){
$leavetypedetail = new HrLeaveTypeDetail();
$leavetypedetail->no_of_days = $request->no_of_days[$key];
$leavetypedetail->employment_type_code = $request->employment_type_code[$key];
$leavetypedetail->leave_type_id = $leavetype->id;
$leavetypedetail->save();
}
DB::commit();
Session::flash('success', 'Leave Type is updated successfully');
return redirect()->route('leave.leave_types.index');
}
catch (\Illuminate\Database\QueryException $e){
DB::rollback();
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
Session::flash('error', 'Duplicate Entry! Please try again');
}
return back();
}
catch (Exception $exception) {
DB::rollback();
Session::flash('error', 'Leave Type update failed!');
return redirect()->route('leave.leave_types.index');
}
}
view blade
<form action="{{route('leave.leave_types.update', ['id'=>$leavetype->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Name:<span style="color:red;">*</span></label>
<input type="text" name="leave_type_name" placeholder="Enter leave type name here" class="form-control" value="{{old('leave_type_name',$leavetype->leave_type_name)}}">
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Code:</label>
<input type="text" name="leave_type_code" placeholder="Enter leave type code here" class="form-control" value="{{old('leave_type_code',$leavetype->leave_type_code)}}">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Description</label>
<textarea rows="2" name="description" class="form-control" placeholder="Enter Description here ..." value="{{old('description',$leavetype->description)}}">{{old('description',$leavetype->description)}}</textarea>
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Employment Type<span style="color:red;">*</span></th>
<th scope="col">Leave Days<span style="color:red;">*</span></th>
<th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
#foreach($leavetypedetails as $leavetypedetail)
<tr>
<td width="60%">
<select class="form-control select2bs4" data-placeholder="Select Employment Type" tabindex="1" name="employment_type_code[]">
<option name="employment_type_code[]" value="{{$leavetypedetail->employmenttype->employment_type_code}}">{{$leavetypedetail->employmenttype->employment_type_name}}</option>
#foreach($employmenttypes as $employmenttype)
<option name="employment_type_code[]" value="{{$employmenttype->employment_type_code}}">{{$employmenttype->employment_type_name}}</option>
#endforeach
</select>
</td>
<td width="35%"><input value="{{$leavetypedetail->no_of_days}}" type="text" name="no_of_days[]" class="form-control" max="120"></td>
<td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.update') }}</button>
<button type="button" onclick="window.location.href='{{route('leave.leave_types.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
addRow();
});
function addRow() {
var addRow = '<tr>\n' +
' <td width="60%"><select class="form-control select2bs4" data-placeholder="Choose Employment Type" tabindex="1" name="employment_type_code[]">\n' +
' <option value="0" selected="true" disabled="true">Select Employment Type</option>\n' +
' #if($employmenttypes->count() > 0 )\n' +
' #foreach($employmenttypes as $employmenttype)\n' +
' <option value="{{$employmenttype->employment_type_code}}">{{$employmenttype->employment_type_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td width="35%"><input type="number" name="no_of_days[]" placeholder="Enter leave days here" class="form-control no_of_days" max="120"></td>\n' +
' <td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
When I submitted the form for update,
I observed that the application save another data (duplicated) the model HrLeaveType into the database.
It replace the value of employment_type_code in the HrLeaveTypeDetail model with the latest row in HrLeaveType.
Why am I having these issues and how do I resolve it?
Thanks

Input Multiple Data Codeigniter

Sorry if this question has been asked before. I would like to ask for help to check my script below. Because when I tried to submit my form with multiple input field it only results in one data, whereas, there should be two data entered into the database.
So, which part of my script is wrong?
Controller
public function add() {
// ... some script before 'else' ...
} else {
$post = $this->input->post();
$result = array();
$total_input = count($post['input_acc_code']);
foreach ($post['input_acc_code'] as $key => $value) {
$result[] = array(
'trans_type' => 'journal',
'form_type' => NULL,
'acc_code' => $post['input_acc_code'][$key],
'acc_type_id' => $post['input_acc_type_id'][$key],
'refference' => '',
'customer_ID' => NULL,
'acc_side' => '',
'debet' => $post['input_debet'][$key],
'credit' => $post['input_credit'][$key],
'summary' => $post['input_note'][$key],
'files' => NULL,
'create_at' => date("Y-m-d H:i:s", strtotime("now"))
);
if($this->model_transaction->savedata('fi_acc_journal', $result) == TRUE) {
$this->session->set_flashdata('alert', 'Success');
redirect(base_url().'admin/transaction');
} else {
$this->session->set_flashdata('alert', 'Failed');
redirect(base_url().'admin/transaction');
}
}
}
}
Model
function savedata($table, $data = array()) {
$this->db->insert_batch($table, $data);
if($this->db->affected_rows() > 0) {
return TRUE;
}
return FALSE;
}
View
<?php $attributes = array('class' => 'form-horizontal', 'id' => '');
echo form_open_multipart(base_url().$this->session->userdata('user_status').'/transaction/add', $attributes);?>
<div class="row">
<div class="col-sm-12 col-md-12 panel-form-input">
<div class="form-group form-group-sm">
<label for="input_datetime" class="col-sm-2 control-label">Tanggal Transaksi</label>
<div class="col-sm-10">
<input type="text" class="input-date form-control" name="input_datetime[]" id="input-date">
<?php echo form_error('input_datetime');?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 panel-form-input">
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-unbordered">
<thead>
<th class="col-25">Account</th>
<th class="col-5">Account Type</th>
<th class="col-35">Notes</th>
<th class="col-15">Debet</th>
<th class="col-15">Credit</th>
<th class="col-5"></th>
</thead>
<tbody>
// First Input Field Form Table
<tr>
<td class="col-25">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<select class="select-transaction input-group-sm form-control" name="input_acc_code[]" id="acc_code_1">
<?php if ($account_list != NULL): ?>
<option>— Choose Account Number —</option>
<?php foreach ($account_list as $value): ?>
<option value="<?php echo $value->acc_code;?>"><?php echo $value->acc_name;?></option>
<?php endforeach;?>
<?php else:?>
<option>— No Data —</option>
<?php endif;?>
</select>
<?php echo form_error('input_acc_code[]');?>
</div>
</div>
</td>
<td class="col-5">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_acc_type_id[]" id="acc_type_id_1">
<?php echo form_error('input_acc_type_id[]');?>
</div>
</div>
</td>
<td class="col-35">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_note[]">
<?php echo form_error('input_note[]');?>
</div>
</div>
</td>
<td class="col-15">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_debet[]">
</div>
</div>
</td>
<td class="col-15">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_credit[]">
</div>
</div>
</td>
<td class="col-5"></td>
</tr>
// Second Input Field Form Table
<tr>
<td class="col-25">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<select class="select-transaction input-group-sm form-control" name="input_acc_code[]" id="acc_code_1">
<?php if ($account_list != NULL): ?>
<option>— Choose Account Number —</option>
<?php foreach ($account_list as $value): ?>
<option value="<?php echo $value->acc_code;?>"><?php echo $value->acc_name;?></option>
<?php endforeach;?>
<?php else:?>
<option>— No Data —</option>
<?php endif;?>
</select>
<?php echo form_error('input_acc_code[]');?>
</div>
</div>
</td>
<td class="col-5">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_acc_type_id[]" id="acc_type_id_1">
<?php echo form_error('input_acc_type_id[]');?>
</div>
</div>
</td>
<td class="col-35">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_note[]">
<?php echo form_error('input_note[]');?>
</div>
</div>
</td>
<td class="col-15">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_debet[]">
</div>
</div>
</td>
<td class="col-15">
<div class="form-group form-group-sm">
<div class="col-sm-12">
<input type="text" class="form-control" name="input_credit[]">
</div>
</div>
</td>
<td class="col-5"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12">
<div class="menu-bar">
<button class="btn btn-md btn-primary" type="submit">Save</input>
</div>
</div>
</div>
<?php echo form_close();?>
Thank you for your help....
Try moving the insert_batch related model call out of the foreach, as otherwise you could just run a straight insert there. First you are building the queries to insert, then after the foreach you insert the multidimensional array!
public function add()
{
$post = $this->input->post();
$result = array();
$total_input = count($post['input_acc_code']);
foreach ($post['input_acc_code'] as $key => $value) {
$result[] = array(
'trans_type' => 'journal',
'form_type' => NULL,
'acc_code' => $post['input_acc_code'][$key],
'acc_type_id' => $post['input_acc_type_id'][$key],
'refference' => '',
'customer_ID' => NULL,
'acc_side' => '',
'debet' => $post['input_debet'][$key],
'credit' => $post['input_credit'][$key],
'summary' => $post['input_note'][$key],
'files' => NULL,
'create_at' => date("Y-m-d H:i:s", strtotime("now"))
);
}
if ($this->model_transaction->savedata('fi_acc_journal', $result) == TRUE) {
$this->session->set_flashdata('alert', 'Success');
redirect(base_url() . 'admin/transaction');
} else {
$this->session->set_flashdata('alert', 'Failed');
redirect(base_url() . 'admin/transaction');
}
}

How to insert multiple rows in laravel 5?

I want to insert an array with an id :
create.blade :
{{ Form::open(array('route' => 'Charge.store','method'=>'POST')) }}
<select id="disabledSelect" class="form-control" name="Facture_id">
<option value="{{ $Facture->id }}" >{{ $Facture->Num }}</option>
</select>
<br/>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Title]" placeholder="libelé"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Quantity]" placeholder="Quantité"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Price]" placeholder="Prix unitaire "/>
</div>
<div class="form-group">
<input type="button" class="btn btn-default" value="Ajouter" onclick="createNew()" />
</div>
<div id="mydiv"></div>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-info">
Cancel
</div>
{{ Form::close() }}
<script>
var i = 2;
function createNew() {
$("#mydiv").append('<div class="form-group">'+'<input type="text" name="rows[' + i +'][Title]" class="form-control" placeholder="libelé"/>'+
'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Quantity]" class="form-control" placeholder="Quantité"/>'+'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Price]" class="form-control" placeholder="Prix unitaire "/>'+'</div>'+'<div class="form-group">'+
'<input type="button" name="" class="btn btn-default" value="Ajouter" onclick="createNew()" />'+
'</div><br/>');
i++;
}
</script>
here is my controller , when I tried to submit the form , it inject rows with value of 0.
What should I do ? I tried to use elequent bolk data , but the problem remain the same:
public function store(Request $request)
{
// validated input request
$this->validate($request, [
'Facture_id' => 'required',
]);
// create new task
$rows = $request->input('rows');
foreach ($rows as $row)
{
$Charges[] = new Charge(array(
'course_id'=>$request->input('Facture_id'),
'Title'=>$row['Title'],
'Quantity'=>$row['Quantity'],
'Price'=>$row['Price'],
));
}
Charge::create($Charges);
return redirect()->route('Charge.index')->with('success', 'Your task added successfully!');
}
You can use insert() method:
foreach ($rows as $row)
{
$charges[] = [
'course_id' => $request->input('Facture_id'),
'Title' => $row['Title'],
'Quantity' => $row['Quantity'],
'Price' => $row['Price'],
];
}
Charge::insert($charges);
Don't forget to add all column names you use to a $fillable array:
$fillable = ['course_id', 'Title', 'Quantity', 'Price'];

Resources