Laravel - Dynamic Input Field Failed to Submit without Displaying any Error - javascript

I have been battling with this issue for some days now. I have a project on Laravel-5.8
I have two model classes
AppraisalGoal
protected $fillable = [
'goal_type_id',
'appraisal_identity_id',
'employee_id',
'company_id',
'is_published',
'is_approved',
'weighted_score',
'employee_comment',
'line_manager_comment',
'goal_title',
'start_date',
'end_date',
'created_by',
'created_at',
'updated_by',
'updated_at',
'is_active'
];
AppraisalGoalDetail
protected $fillable = [
'name',
'company_id',
'appraisal_goal_id',
'kpi_description',
'appraisal_doc',
'activity',
'created_by',
'created_at',
'updated_by',
'updated_at',
'is_active'
];
Appraisal Goal is the main model
StoreAppraisalGoalRequest
class StoreAppraisalGoalRequest extends FormRequest
{
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',
'appraisal_goal_id' => 'required',
'kpi_description' => 'required|max:300',
'activity' => 'required|max:300',
];
}
}
Controller
public function create()
{
$userCompany = Auth::user()->company_id;
$identities = DB::table('appraisal_identity')->select('appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$goaltypes = AppraisalGoalType::where('company_id', $userCompany)->get();
$categories = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('appraisal.appraisal_goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities);
}
public function store(StoreAppraisalGoalRequest $request)
{
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$appraisal_identity_id = AppraisalIdentity::where('company_id', $userCompany)->where('is_current',1)->value('id');
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $appraisal_identity_id;
$goal->employee_id = $request->employee_id;
$goal->weighted_score = $request->weighted_score;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new AppraisalGoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->appraisal_doc = $request->application_doc[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->company_id = Auth::user()->company_id;
$goaldetail->created_by = Auth::user()->id;
$goaldetail->created_at = date("Y-m-d H:i:s");
$goaldetail->is_active = 1;
$goaldetail->save();
}
Session::flash('success', 'Appraisal Goal is created successfully');
return redirect()->route('appraisal.appraisal_goals.index');
} catch (Exception $exception) {
Session::flash('danger', 'Appraisal Goal creation failed!');
return redirect()->route('appraisal.appraisal_goals.index');
}
}
create.blade
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title">Creating My 3 + 1 Goals: <b>{{$identities->appraisal_name}}</b></h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form method="POST" action="{{route('appraisal.appraisal_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 click on submit button, it did not save any record but redirected to the index page. No error indicated, even in the Browser Network.
Then, I added this before the try{} in the store function of the controller:
$data = $request->all(); print_r($data); exit;
and I got this result:
Array ( [_token] => KbnpT9MAFywHJBfVoWllKvr2ELSsRNZmWM4B5Eui [goal_type_id] => 2 [appraisal_identity_id] => 8 [goal_title] => goal title1 [goal_description] => [activity] => Array ( [0] => activity2 [1] => activity3 ) [kpi_description] => Array ( [0] => kpi description2 [1] => kpi description3 ) [weighted_score] => 20 [start_date] => 2020-02-03 [end_date] => 2020-02-29 )
But when I added
print_r($goal); exit;
after
$goal->save();
There was no result.
How do I get this sorted out?
Thank you.

sometimes some dev using try catch statement but forget to look whats wrong while the code thrown an exception. so lets change your catch statement to this for figure out whats wrong.
}catch (Exception $exception) {
dd($exception->getMessage());
Session::flash('danger', 'Appraisal Goal creation failed!');
return redirect()->route('appraisal.appraisal_goals.index');
}

Related

updating the options of the "admin_id" select element

In my project i want to create difference admins for colleges ,departments and laboratorys , i u used Ajax for fetching data of admin id depends on the admin type input and i also use a logic in controller as the following in my controller :
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|',
'password' => 'required',
'roles' => 'required',
'admin_type'=>'required',
'admin_id'=>'required'
]);
$adminType = $request->input('admin_type');
$adminId = $request->input('admin_id');
$input = $request->all();
// $input['password'] = Hash::make($input['password']);
$user = User::create($input);
if ($adminType == 'colleges') {
$user->colleges()->attach($adminId);
} else if ($adminType == 'departments') {
$user->departments()->attach($adminId);
} else if ($adminType == 'laboratories') {
$user->laboratories()->attach($adminId);
}
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
public function getAdminId(Request $request)//for getting admin ids depends on the admin_type
{
$adminType = $request->admin_type;
$options = '';
if ($adminType == 'college') {
$colleges = College::all();
foreach ($colleges as $college) {
$options .= '<option value="'.$college->id.'" id="'.$college->id.'">'.$college->name.'</option>';
}
} elseif ($adminType == 'department') {
$departments = Department::all();
foreach ($departments as $department) {
$options .= '<option value="'.$department->id.'">'.$department->name.'</option>';
}
} elseif ($adminType == 'laboratory') {
$laboratories = Laboratory::all();
foreach ($laboratories as $laboratory) {
$options .= '<option value="'.$laboratory->id.'">'.$laboratory->name.'</option>';
}
}
return '<select name="admin_id" id="admin_id" class="form-control">'.$options.'</select>';;
}
in my route i have this for Ajax
Route::get('get/admin_id', [App\Http\Controllers\UserController::class, 'getAdminId'])->name('get.admin_id');
in my blade template
#extends('layouts.mainlayout')
#section('content')
<section class="content">
<div class="body_scroll">
<div class="block-header">
<div class="container-fluid">
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<div class="body">
<h2 class="card-inside-title" >User Registration</h2>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="POST" action="{{ route('users.store') }}">
#csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" placeholder="name" name = "name" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="email"name = "email">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<div class="form-group ">
<label for="role">Roles:</label>
<select name="roles[]" id="roles" class= "form-control show-tick ms select2" multiple data-placeholder="Select Roles">
#foreach($roles as $tag)
<option value="{{$tag}}"
>{{$tag}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="admin_type">Admin Type</label>
<select name="admin_type" id="admin_type" class="form-control">
<option value="college">College</option>
<option value="department">Department</option>
<option value="laboratory">Laboratory</option>
</select>
</div>
<div class="form-group">
<label for="admin_id">Admin ID</label>
<select name="admin_id" id="admin_id" class="form-control">
<option value=""> </option>
</select>
</div>
<div>
<button class="btn btn-raised btn-primary waves-effect" onclick="this.form.submit()" type="submit">SUBMIT</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
#endsection
#section('scripts')
<script>
$(document).ready(function(){
$('#admin_type').on('change', function(){
var adminType = $(this).val();
$.ajax({
type:'GET',
url: '{{ route('get.admin_id') }}',
data: { admin_type: adminType },
success:function(data){
console.log(data);
$('#admin_id').append(data);
}
});
});
});
</script>
#endsection
and in console l got what i want like this "habtewolddf" but in the blade page the options are not coming, I dont know why it is not working any one who can help me please please???
You are appending select with another select. Try change <select> in blade file by <div> or even better - instead of .append() use .replaceWith() :
$('#admin_type').on('change', function(){
var adminType = $(this).val();
$.ajax({
type:'GET',
url: '{{ route('get.admin_id') }}',
data: { admin_type: adminType },
success:function(data){
console.log(data);
$('#admin_id').replaceWith(data); // Here
}
});
});

Laravel 9: Redirect page window.location in javascript doesn't work when updating data

I am trying to update data in modals/pop-ups using jquery ajax. when I click the UPDATE Button, a page appears containing json data and the data has been successfully updated to the database.
{"success":true,"message":"Data Berhasil Diudapte!","data":{"id":6,"id_karyawan":"3","id_settingalokasi":"8","id_jeniscuti":"6","durasi":"3","mode_alokasi":"Berdasarkan Karyawan","tgl_masuk":null,"tgl_sekarang":null,"aktif_dari":"2022-01-02","sampai":"2022-12-31","created_at":"2022-12-15T06:21:04.000000Z","updated_at":"2022-12-21T04:09:04.000000Z"}}
with status 200 on the network
display on the network
but when double click on the data id on that network, an error appears like the following:
error when double click I don't know which url is meant in the error, so I'm quite confused about this error
this is my controller for function edit and update leave data:
//get data alokascuti
public function edit($id)
{
$alokasicuti = Alokasicuti::find($id);
return response()->json([
'success' => true,
'message' => 'Data Alokasi cuti',
'data' => $alokasicuti
]);
// dd($alokasicuti);
}
public function update(Request $request, $id)
{
$alokasicuti = Alokasicuti::find($id);
if($request->id_jeniscuti == 1)
{
$validate = $request->validate([
'id_karyawan' => 'required',
'id_settingalokasi'=> 'required',
'id_jeniscuti' => 'required',
'tgl_masuk' => 'required',
'tgl_sekarang' => 'required',
'aktif_dari' => 'required',
'sampai' => 'required',
]);
$alokasicuti->update([
'id_karyawan' =>$request->id_karyawan,
'id_settingalokasi'=> $request->id_settingalokasi,
'id_jeniscuti' =>$request->id_jeniscuti,
'durasi' =>$request->durasi,
'mode_alokasi' =>$request->mode_alokasi,
'tgl_masuk' => Carbon::parse($request->tgl_masuk)->format('Y-m-d'),
'tgl_sekarang' => Carbon::parse($request->tgl_sekarang)->format('Y-m-d'),
'aktif_dari' => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
'sampai' => Carbon::parse($request->sampai)->format('Y-m-d'),
]);
return response()->json([
'success' => true,
'message' => 'Data Berhasil Diudapte!',
'data' => $alokasicuti
]);
}else
{
$validate = $request->validate([
'id_karyawan' => 'required',
'id_settingalokasi'=> 'required',
'id_jeniscuti' => 'required',
'aktif_dari' => 'required',
'sampai' => 'required',
]);
$alokasicuti->update([
'id_karyawan' =>$request->id_karyawan,
'id_settingalokasi'=> $request->id_settingalokasi,
'id_jeniscuti' =>$request->id_jeniscuti,
'durasi' =>$request->durasi,
'mode_alokasi' =>$request->mode_alokasi,
'tgl_masuk' =>NULL,
'tgl_sekarang' =>NULL,
'aktif_dari' => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
'sampai' => Carbon::parse($request->sampai)->format('Y-m-d'),
]);
return response()->json([
'success' => true,
'message' => 'Data Berhasil Diudapte!',
'data' => $alokasicuti
]);
}
}
this is the code in editallocation.blade.php along with the script:
<!-- script untuk mengambil data alokasi cuti -->
<script type="text/javascript">
$('body').on('click','.btn-editalokasi',function()
{
var id_alokasi =$(this).data('alokasi');
// console.log(id_alokasi);
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
url: "/edit-alokasi/"+id_alokasi,
type: "GET",
cache: false,
success: function (response) {
// console.log(response);
$('#id_alokasi').val(response.data.id);
$("#idjeniscuti").val(response.data.id_jeniscuti);
$("#idsettingalokasi").val(response.data.id_settingalokasi);
$("#id_karyawan").val(response.data.id_karyawan);
$("#duration").val(response.data.durasi);
$("#modealokasi").val(response.data.mode_alokasi);
// $("#tglmasuk").val(response.data.tgl_masuk);
// $("#tglsekarang").val(response.data.tgl_sekarang);
$("#datepicker-autoclosea3").val(response.data.aktif_dari);
$("#datepicker-autoclosea4").val(response.data.sampai);
}
});
});
</script>
<!-- script untuk menyimpan data update-->
<script type="text/javascript">
$(".input").click(function(e) {
e.preventDefault();
//nama variabel | id field pada form | value
var id_alokasi = $("#id_alokasi").val();
var id_settingalokasi= $("idsettingalokasi").val();
var id_jeniscuti = $("#idjeniscuti").val();
var id_karyawan = $("#id_karyawan").val();
var durasi = $("#duration").val();
var mode_alokasi = $("#modealokasi").val();
var tgl_masuk = $("#tglmasuk").val();
var tgl_sekarang = $("#tglsekarang").val();
var aktif_dari = $("#datepicker-autoclosea3").val();
var sampai = $("#datepicker-autoclosea4").val();
var token = $('meta[name="csrf-token"]').attr('content');
});
$.ajax({
url: "/updatealokasi/{$id_alokasi}",
type:"PUT",
data: {
"id":id_alokasi,
"id_settingalokasi": id_settingalokasi,
"id_jeniscuti": id_jeniscuti,
"id_karyawan": id_karyawan,
"durasi": durasi,
"mode_alokasi": mode_alokasi,
"tgl_masuk": tgl_masuk,
"tgl_sekarang": tgl_sekarang,
"aktif_dari":aktif_dari,
"sampai": sampai,
"_token": token,
},
success: function(response) {
window.location = "http://127.0.0.1:8000/alokasicuti";
$('#aid'+ response.id +' td:nth-child(1)').text(response.id_karyawan);
$('#aid'+ response.id +' td:nth-child(2)').text(response.id_jeniscuti);
$('#aid'+ response.id +' td:nth-child(3)').text(response.durasi);
$('#aid'+ response.id +' td:nth-child(4)').text(response.mode_alokasi);
$('#aid'+ response.id +' td:nth-child(5)').text(response.aktif_dari);
$('#aid'+ response.id +' td:nth-child(6)').text(response.sampai);
$(".input")[0].reset();
// $('#aid'+ response.id +' td:nth-child(1)').text(response.id_settingalokasi);
// $('#aid'+ response.id +' td:nth-child(6)').text(response.tgl_masuk);
// $('#aid'+ response.id +' td:nth-child(7)').text(response.tgl_sekarang);
},
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="modal fade" data-alokasi="{{$data->id}}" id="editalokasi" tabindex="-1" role="dialog" aria-labelledby="editalokasi" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="editalokasi">Edit Alokasi Cuti</h4>
</div>
<div class="modal-body">
<form class="input" action="/updatealokasi/{{$data->id}}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="panel-body">
<div class="col-md-6">
<input type="hidden" id="id_alokasi" name="id" value="{{$data->id}}">
<input type="hidden" name="id_settingalokasi" id="idsettingalokasi" value="{{$data->id_settingalokasi}}">
<div class="form-group col-sm">
<label for="id_jeniscuti" class="col-form-label">Kategori Cuti</label>
<select name="id_jeniscuti" id="idjeniscuti" class="form-control">
<option value="{{$data->id_jeniscuti}}" selected>{{$data->jeniscutis->jenis_cuti}}</option>
#foreach ($jeniscuti as $jenis)
<option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}</option>
#endforeach
</select>
</div>
<div class="form-group col-sm" id="idkaryawan">
<label for="id_karyawan" class="col-form-label">Karyawan</label>
<select name="id_karyawan" id="id_karyawan" class="form-control">
<option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
#foreach ($karyawan as $data)
<option value="{{ $data->id }}">{{ $data->nama }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="durasi" class="col-form-label">Durasi (Hari)</label>
<input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" readonly>
</div>
<div class="form-group">
<label for="mode_alokasi" class="col-form-label">Mode Alokasi</label>
<input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" id="modealokasi" readonly>
</div>
</div>
<div class="col-md-6">
<div class="" id="tglmulai">
<div class="form-group">
<label for="tgl_masuk" class="form-label">Tanggal Masuk</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tglnow">
<div class="form-group">
<label for="tgl_sekarang" class="form-label">Tanggal Sekarang</label>
<div class="input-group">
<input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalmulai">
<div class="form-group">
<label for="tgl_mulai" class="form-label">Aktif Dari</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalselesai">
<div class="form-group">
<label for="sampai" class="form-label">Sampai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" name="submit" value="save" id="update">Update</button>
</div>
</form>
</div>
</div>
</div>
</div>
please help me solve this problem, because I'm still new to jquery ajax and I don't know much about jquery ajax yet.

Add Dynamic Rows with dependent dropdown in alpine js

Hi, I'm using Alpine.js in laravel blade and I want to build a dependent dropwdown with dynamic add new row and remove row and add new rows works fine but when I select the parent dropdown it's lost all other dependent dropdown values. Can you help to how I can get rid of ? Thanks
my-blade-file.php
{{-- add or remove dropdown seciton --}}
<div x-data="addNewWithDropdown()">
<div class="col-2">
<button class="btn bg-gradient-info custom-add-icon-btn" type="button" name="button" #click="addNewField()">
<i class="fa-solid fa-plus"></i> Add New
</button>
</div>
<div class="col-12">
<template x-for="(field, index) in fields" :key="field.id">
<div class="add-input" x-data="devicesData()">
<div class="row">
<div class="col-6">
<label class="form-label mt-0">Select Brand </label>
<select :id="'row-' + index" x-model="brand" class="form-control" name="brand[]" #change="getItems()">
<option value="-1">Select Brand</option>
#foreach ($brands as $brand)
<option value="{{ $brand->id }}">{{ $brand->brand_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="row mt-2 align-items-center">
<div class="col-6">
<label class="form-label mt-0">Device Name</label>
<div class="form-group mb-0">
<select :id="'row-' + index" x-model="item" class="form-control" name="item[]">
<option value="-1">Select Device</option>
<template x-for="(item, index) in items" :key="index">
<option :value="item.id" x-text="item.item_name"></option>
</template>
</select>
</div>
</div>
<div class="col-2">
<button class="btn bg-gradient-danger custom-add-icon-btn" type="button" name="button"
#click="removeField(field)">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
</div>
</template>
</div>
</div>
<script>
function addNewWithDropdown() {
return {
fields: [],
addNewField() {
this.fields.push({
id: new Date().getTime() + this.fields.length
});
},
removeField(field) {
this.fields.splice(this.fields.indexOf(field), 1);
}
}
}
function devicesData() {
return {
brand: '',
items: {},
item: '',
getItems() {
fetch(`api/my-api-route/${this.brand}`)
.then((res) => res.json())
.then((res) => {
this.items = res;
})
}
}
}
</script>
my-controller.php
<?php
public function today_buy_sales(){
$brands = Brand::orderBy('brand_name', 'asc')->get();
return view('layouts.my-blade-view', compact('brands'));
}
public function getItems($id){
$items = Item::where('brand_id', $id)->get();
return response()->json($items);
}
?>

laravel Livewire wire:click not firing the function

I want to do a SPA with laravel livewire, i want to use wire:click to fire a funtion in the component but it not working , excuse me if the code mess its my first time posting here and i am not sure of what to post here of my code to make these problem solve thank you
main.blade.php
#section('content')
<div>
<div class="row justify-content-center">
<div class="col-12">
<div class="card my-3">
<!-- header -->
<div class="card-header d-inline-flex">
<h3 class='mr-2'>Categories</h3>
<div>
Add NewCategory
</div>
</div><!-- header -->
<div class="card-body">
<!-- alerts -->
#include('admin.includes.alerts.errors')
#include('admin.includes.alerts.success')
<!-- alerts -->
<!-- if True , create form will show , if not will stay disabled -->
#if ($showCreateForm)
#livewire('admin.category.create' )
#endif
<!-- if True , create form will show , if not will stay disabled -->
<!-- Table -->
<div class="table-responsive">
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Name</th>
<th>Slug</th>
<th>Status</th>
<th>Parent</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>{{$category->id}}</td>
{{-- <td>{{storage_path(app\livewire-tmp\$category->image)}}" /></td> --}}
<td>{{$category->name}}</td>
<td>{{$category->slug}}</td>
<td class=" {{$category->isActive()==='Active'? 'text-success':'text-danger'}}">
{{$category->isActive()}}</td>
<td>{{ !empty($category->parent) ? $category->parent->name:'' }}</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Image</th>
<th>Name</th>
<th>Slug</th>
<th>Status</th>
<th>Parent</th>
<th>Action</th>
</tr>
</tfoot>
</table>
<div>
{!!$categories->links()!!}
</div>
</div>
<!-- Table -->
</div><!-- body -->
</div>
</div>
</div>
</div>
#endsection
and The Component Main.php ,
<?php
namespace App\Http\Livewire\Admin\Category;
use App\Models\Admin\Category;
use Livewire\Component;
use Livewire\WithPagination;
class Main extends Component
{
use WithPagination;
protected $categories;
public $showCreateForm = false;
public $showEditForm = false;
public function render()
{
$categories = Category::orderBy('id','desc')->paginate(12);
return view('livewire.admin.category.main',[
'categories' => $categories,
]) ->layout('layouts.admin');
}
public function createCategory()
{
$this->showCreateForm = !$this->showCreateForm;
}
public function update_Category($id)
{
$categories = Category::whereId($id);
if ($categories) {
$this->emit('getCategoryid' , $categories);
$this->showEditForm = !$this->showEditForm;
$this->showCreateForm = false;
}
}
public function delete_Category($id)
{
$this->showCreateForm = !$this->showCreateForm;
}
}
//// Update ////
i tried iRestWeb Answer, I think it the right answer but i dont even understand what happening its 100% javascript related and its not my field of expertise , so here's my full code i hope some one understand , and again sorry if my code messy and give you hard time , thank youu.
create.blade.php
<div>
<form role="form" wire:submit.prevent="create" method="POST" enctype="multipart/form-data">
#csrf
<div class="card-body">
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="exampleInputEmail1">Parent</label>
<select type="select" class="form-control" id="exampleInputEmail1" wire:model="parent_id" name="parent_id">
<option selected value> -- select an option -- </option>
{{-- #if (is_array($categories) || is_object($categories) || !empty($categories)) --}} #foreach ($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach {{-- #endif --}}
</select>
</div>
</div>
<!-- 1 -->
<div class="col-6">
<div class="form-group">
<label for="exampleInputPassword1">Category Name</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="name" name="name"> #error('name') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- 2 -->
<div class="col-6">
<div class="form-group">
<label for="exampleInputPassword1">Slug Name</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="slug" name="slug"> #error('slug') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- 3 -->
<div class="col-6">
<div class="form-group">
<label for="exampleFormControlFile1">Image</label>
<input type="file" wire:model="image" class="form-control-file" id="exampleFormControlFile1" name="image"> #error('image') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- 4 -->
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" wire:model="is_active" name="is_active">
<label class="form-check-label" for="exampleCheck1">is Active</label> #error('is_active') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
Create.php
<?php
namespace App\Http\Livewire\Admin\Category;
use Livewire\Component;
use App\Models\Admin\Category;
use Livewire\WithFileUploads;
use Illuminate\Support\Str;
use Livewire\WithPagination;
use Intervention\Image\Facades\Image;
class Create extends Component
{
use WithFileUploads;
use WithPagination;
public $slug , $name , $image , $parent_id , $is_active;
protected $rules = [
'slug' => 'required|unique:categories,slug',
'name' => 'required',
'image'=> 'nullable|image|max:1024'
];
protected $categories;
public function render()
{
$categories = Category::orderBy('id','desc')->paginate(12);
return view('livewire.admin.category.create' , [
'categories' => $categories,
]);
}
public function create()
{
$this->validate();
$data = [
'name' => $this->name,
'slug' => $this->slug,
'is_active'=> $this->is_active,
'image'=> $this->image,
'parent_id'=> $this->parent_id,
];
//image upload
try {
if ($image = $this->image) {
$filename = Str::slug($this->name).'.'.$image->getClientOriginalExtension();
$path = public_path('assets/image/'.$filename);
Image::make($image->getRealPath())->save($path,100);
}
Category::create($data);
$this->reset();
return $this->addError('success' , 'Created Successfuly');
} catch (\Throwable $th) {
return $this->addError('error', 'Something Wrong Happens');
}
}
}
edit.blade.php
<div>
<form role="form" method="POST" enctype="multipart/form-data" wire:submit.prevent="update">
#csrf
<div class="card-body">
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="exampleInputEmail1">Parent</label>
<select type="select" class="form-control" id="exampleInputEmail1" wire:model="parent_id" name="parent_id">
<option></option>
{{-- #if (is_array($categories) || is_object($categories) || !empty($categories)) --}} #foreach ($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach {{-- #endif --}}
</select>
</div>
</div>
<!-- 1 -->
<div class="col-6">
<div class="form-group">
<label for="exampleInputPassword1">Category Name</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="name" value='{{$category->name}}' name="name"> #error('name') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- 2 -->
<div class="col-6">
<div class="form-group">
<label for="exampleInputPassword1">Slug Name</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="slug" name="slug" value='{{$category->slug}}'> #error('slug') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- 3 -->
<div class="col-6">
<div class="form-group">
<label for="exampleFormControlFile1">Image</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1" name="image">
<img value='{{$category->image}}' alt="" srcset=""> #error('image') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- 4 -->
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" wire:model="is_active" name="is_active">
<label class="form-check-label" for="exampleCheck1">is Active</label> #error('is_active') <span class="error text-danger">{{ $message }}</span> #enderror
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
Edit.php (uncompleted Task)
<?php
namespace App\Http\Livewire\Admin\Category;
use Livewire\Component;
use App\Models\Admin\Category;
class Edit extends Component
{
protected $categories , $cat_id;
public $slug , $name , $image , $old_image , $parent_id , $is_active;
protected $listeners = ['getCategoryid'=>'getID'];
public function mount()
{
$this->categories = Category::whereId($this->cat_id)->first();
}//mout
public function render()
{
$categories = Category::all();
return view('livewire.admin.category.edit' , [
'categories' => $categories,
]);
}//render
public function update($id)
{
}//update
public function getID($categories)
{
$this->categories = $categories;
// Data
$this->slug = $this->$categories['slug'];
$this->name = $this->$categories['name'];
$this->image = $this->$categories['image'];
$this->old_image = $this->$categories['old_image'];
$this->parent_id = $this->$categories['parent_id'];
$this->is_active = $this->$categories['is_active'];
}//getID
}
All HTML code should be covered with single <div>. Then it will work.
add liveWire's css and js in the base.blade.php file and it works:
<head>
...
#livewireStyles
</head>
<body>
...
#livewireScripts
</body>
</html>
You don't need the :click event to do this, you can simply use:
wire:$toggle('property')
And you don't need to use the a tag; you can simply use the button tag. So your button code will look like this:
<button type="button" wire:$toggle='showCreateForm' class="btn btn-success">Add New Category</button>
I think this will help you
Add New Category
use <livewire:styles /> and <livewire:scripts />
(instead #livewireStyles and #livewireScripts)

Submit images using dropzone in laravel with other attributes of a form

I am trying to submit images from dropzone and other text field. but dropzone works separately how can i submit dropzone files with other data of form in controller. I need to submit form with files on button click in the controller method.
HTML Form
<form method="post" enctype="multipart/form-data" id="case-form" action="{{route('case-submit')}}">
#csrf
<div class="box-body form-element" >
<div class="row">
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Doctor</label>
<input class="form-control" type="text" name="doctor_name" id="doctor_name" required max="50">
</div>
</div>
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Upper Aligner</label>
<input class="form-control" type="number" name="upper_aligner" id="upper_aligner" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Portal</label>
<select class="form-control col-sm-10" name="portal_id" id="portal" required>
#foreach($portal as $obj)
<option value="{{$obj->id}}">{{$obj->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Patient</label>
<input class="form-control" type="text" name="patient_name" id="patient_name" required max="50">
</div>
</div>
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Lower Aligner</label>
<input class="form-control" type="number" id="lower_aligner" name="lower_aligner" required>
</div>
</div>
</div>
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-12">
<div class="col-sm-4" runat="server">
<label for="exampleInputFile">File Before</label>
<label class="control-label file_before" style="display:none; color: #fc4b6c;"><i class="fa fa-times-circle-o"></i></label>
<div class="file-drop-area border dropzone clsbox" id="mydropzone">
</div>
</div>
<div class="col-sm-4" runat="server">
<div class="form-group">
<label for="exampleInputFile">File After</label>
<label class="control-label file_after" style="display:none; color: #fc4b6c;"><i class="fa fa-times-circle-o"></i></label>
<div class="file_after-drop-area border dropzone clsbox" id="fileafterdropzone">
</div>
</div>
</div>
<div class="col-sm-4">
<label for="exampleInputFile">IPR Form</label>
<div class="ipr_form-drop-area border">
<input type="file" id="ipr_form" name="ipr_form" class="ipr_form files" accept="image/*" required>
<p class="message">Drag your files here or click in this area.</p>
</div>
<img src="" id="profile-img-tag" width="200px" />
</div>
</div>
</div>
<!-- /.row -->
</div>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right">Submit Case</button>
</div>
<!-- /.box-body -->
</form>
Javascript
<script src="{{asset('public/js/dropzone.js')}}"></script>
<script>
Dropzone.autoDiscover = false;
// Dropzone class:
var myDropzone = new Dropzone("div#mydropzone", {
url: "{{route('case-submit')}}",
acceptedFiles:'.stl',
addRemoveLinks: true,
autoProcessQueue:false,
params: {
_token: "{{csrf_token()}}"
},
});
var myDropzone = new Dropzone("div#fileafterdropzone", {
url: "{{route('case-submit')}}",
acceptedFiles:'.stl',
addRemoveLinks: true,
autoProcessQueue:false,
params: {
_token: "{{csrf_token()}}"
},
});
</script>
$(document).ready(function(e){
// Submit form data via Ajax
$("#case-form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '{{route('case-submit')}}',
data: new FormData(this),
dataType: 'html',
contentType: false,
cache: false,
processData:false,
success: function(response){
},
error: function(response){
}
});
});
});
</script>
Controller
public function caseSubmit(Request $request)
{
$case_number = $request->input('case_number');
$patient_name = $request->input('patient_name');
$doctor_name = $request->input('doctor_name');
$portal_id = $request->input('portal_id');
$date = date("Y-m-d H:m:s");
$user_id = Auth::id();
$caseInputData = ['patient_name' => $patient_name,
'doctor_name' => $doctor_name,
'case_number' => $case_number,
'created_at' => $date,
'user_id' => $user_id,
'portal_id' => $portal_id
];
$case = new Cases();
$case_data = $case->storePatientCase($caseInputData);
$caseId = $case_data->id;
$caseNumber = $case_data->case_number;
}
if ($caseId != null && $caseId > 0) {
$filesBefore = $request->file('file_before');
$no_of_files_attached = count($filesBefore);
$files_array = array();
foreach ($filesBefore as $fileBefore) {
$fileName = $fileBefore->getClientOriginalName();
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesBefore/' . $revisions;
$fileBefore->move($pathToStoreFile, $fileName);
$files_array[] = $fileName;
}
$filesAfter = $request->file('file_after');
$no_of_files_attached = count($filesAfter);
$afterfileArray = array();
foreach ($filesAfter as $fileAfter) {
$afterfileName = $fileAfter->getClientOriginalName();
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesAfter/' . $revisions;
$fileAfter->move($pathToStoreFile, $afterfileName);
$afterfileArray = $afterfileName;
}
$iprForm = $request->file('ipr_form');
$ipr_form = $iprForm->getClientOriginalName();
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/ipr_form/' . $revisions;
$iprForm->move($pathToStoreFile, $ipr_form);
$unique_url = URL::to('/').'/'.$case_number.'/'.uniqid();
$data_array = [
'case_id' => $caseId,
'operator_id' => $request->input('operator_id'),
'upper_aligner' => $request->input('upper_aligner'),
'lower_aligner' => $request->input('lower_aligner'),
'file_before' => json_encode($files_array),
'file_after' => json_encode($afterfileArray),
'ipr_form' => $ipr_form,
'updated_at' => null,
'created_at' => $date,
'revisions' => $revisions,
'url' => $unique_url,
];
}
How can i get files in controller with other text data and submit data in database using this method caseSubmit

Categories

Resources