Input Multiple Data Codeigniter - 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');
}
}

Related

Showing success message but not stored into database laravel

Here is the code for controller:
public function save_product(Request $request){
$request->validate([
'product_name' => 'required',
'product_price' => 'required',
'product_category' => 'required',
'description' => 'nullable',
'image1' => 'required',
'image2' => 'nullable',
'image3' => 'nullable',
], [
'product_name.required' => 'Product name field required',
'product_price.required' => 'Asking price field required',
'product_category.required' => 'Product category field required',
'image1.required' => 'You need a upload image-1 field',
]);
if($request->hasFile('image1') || $request->hasFile('image2') || $request->hasFile('image3')){
$file1 = $request->file('image1');
$file2 = $request->file('image2');
$file3 = $request->file('image3');
$text1 = $file1->getClientOriginalExtension();
$text2 = $file2->getClientOriginalExtension();
$text3 = $file3->getClientOriginalExtension();
$fileName1 = time().'.'.$text1;
$fileName2 = time().'.'.$text2;
$fileName3 = time().'.'.$text3;
$file1->move('uploads/product_image', $fileName1);
$file2->move('uploads/product_image', $fileName2);
$file3->move('uploads/product_image', $fileName3);
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
}
return redirect()->route('add_product')
->with('success','Successfully added Product!');
}
Here is the code for blade template:
#extends('admin.layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
#include('pages.partials.flash_message')
</div>
</div>
</div>
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>Add Product</h2>
</div>
<div class="card-body">
<form action="{{route('save_product')}}" method="POST">
#csrf
<div class="form-group">
<label for="exampleFormControlSelect12">Select Category</label>
<input type="text" class="form-control" placeholder="Enter Arrival Time"
id="exampleFormControlSelect12" name="product_category" list="product_category"
autocomplete="off">
<datalist class="form-control" id="product_category" style="display: none" >
<option value="Women Clothes"></option>
<option value="Jewellery"></option>
<option value="Shoes"></option>
<option value="Sun Glass"></option>
<option value="Hair Band"></option>
</datalist>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-1</label>
</div>
#if ($errors->has('image1'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image1') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image1" class="custom-file-input" id="inputGroupFile01"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-2</label>
<small>*Optional</small>
</div>
#if ($errors->has('image2'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image2') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image2" class="custom-file-input" id="inputGroupFile02"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-3</label>
<small>*Optional</small>
</div>
#if ($errors->has('image3'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image3') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image3" class="custom-file-input" id="inputGroupFile03"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Product Name or Title</label>
<input type="text" name="product_name" class="form-control"
id="exampleFormControlInput1" placeholder="Enter Product Name or Title">
#if ($errors->has('product_name'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_name') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Asking Price</label>
<input type="number" name="product_price" class="form-control"
id="exampleFormControlInput2" placeholder="Enter Asking Price">
#if ($errors->has('product_price'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_price') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Product Description</label>
<textarea class="form-control" name="product_description"
id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<div class="form-footer pt-4 pt-5 mt-4 border-top">
<button type="submit" class="btn btn-primary btn-default">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Route:
Route::post('/admin/add_product','App\Http\Controllers\Admin\AdminController#save_product')
->name('save_product')->middleware('admin');
Model:
protected $fillable = [
'product_name',
'product_category',
'product_price',
'description',
'image1',
'image2',
'image3',
];
Migration:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_category');
$table->string('product_price');
$table->text('description')->nullable();
$table->string('image1');
$table->string('image2')->nullable();
$table->string('image3')->nullable();
$table->timestamps();
});
}
I can't find any error in my code please help me to find out. Thanks in advance.
You have to make separate if conditions for each image. Try this:
$fileName1='';
$fileName2='';
$fileName3='';
if($request->hasFile('image1')) {
$file1 = $request->file('image1');
$text1 = $file1->getClientOriginalExtension();
$fileName1 = time() . '.' . $text1;
$file1->move('uploads/product_image', $fileName1);
}
if($request->hasFile('image2')) {
$file2 = $request->file('image2');
$text2 = $file2->getClientOriginalExtension();
$fileName2 = time() . '.' . $text2;
$file2->move('uploads/product_image', $fileName2);
}
if($request->hasFile('image3')) {
$file3 = $request->file('image3');
$text3 = $file3->getClientOriginalExtension();
$fileName3 = time() . '.' . $text3;
$file3->move('uploads/product_image', $fileName3);
}
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
if($product){
return redirect()->route('add_product')->with('success','Successfully added Product!');
}
else{
return redirect()->back()->with('error','Error!');
}
using enctype="multipart/form-data" inside form tag .

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

Method App\Http\Livewire\Product::extension does not exist

I am learning laravel livewire, and this is my first time using livewire.
I am having trouble running my code on Laravel 8 with laravel-livewire. When I click submit always showing an error like that.
I'm don't know what's wrong and how to fix this
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Livewire\Product;
Route::get('/products', Product::class);
Controller
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Product as ProductModel;
use Illuminate\Support\Facades\Storage;
class Product extends Component
{
use WithFileUploads;
public $name, $image, $description, $qty, $price;
public function previewImage()
{
$this->validate([
'image' => 'image|max:2048'
]);
}
public function store()
{
$this->validate([
'name' => 'required',
'image' => 'image|max:2048|required',
'description' => 'required',
'qty' => 'required',
'price' => 'required',
]);
$imageName = md5($this->image.microtime().'.'. $this->extension());
Storage::putFileAs(
'public/images',
$this->image,
$imageName
);
ProductModel::create([
'name' => $this->name,
'image' => $imageName,
'description' => $this->description,
'qty' => $this->qty,
'price' => $this->price
]);
session()->flash('info', 'Product created sSccessfully');
$this->name = '';
$this->image = '';
$this->description = '';
$this->qty = '';
$this->price = '';
}
}
In this is my blade code, i hope someone can help me. Thanks
<div>
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<h2 class="font-weight-bold mb-3">Product List</h2>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Image</th>
<th>Description</th>
<th>Qty</th>
<th>Price</th>
</tr>
</thead>
<tbody>
#foreach($products as $index=>$product)
<tr>
<td>{{ $index+1 }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->image }}</td>
<td>{{ $product->description }}</td>
<td>{{ $product->qty }}</td>
<td>{{ $product->price }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-body">
<h2 class="font-weight-bold mb-3">Create Product</h2>
<form wire:submit.prevent="store">
<div class="form-group">
<label>Product Name</label>
<input wire:model="name" type="text" class="form-control">
#error('name') <small class="text-danger">{{ $message }}</small> #enderror
</div>
<div class="form-group">
<label>Product Image</label>
<div class="custom-file">
<input wire:model="image" type="file" class="custom-file-input" id="customFile">
<label for="customFile" class="custom-file-label">Choose Image</label>
</div>
#error('image') <small class="text-danger">{{ $message }}</small> #enderror
</div>
#if($image)
<label class="mt-2">Image Preview</label>
<img src="{{ $image->temporaryUrl() }}" class="img-fluid" alt="Preview Image">
#endif
<div class="form-group">
<label>Description</label>
<textarea wire:model="description" class="form-control"></textarea>
#error('description') <small class="text-danger">{{ $message }}</small> #enderror
</div>
<div class="form-group">
<label>Qty</label>
<input wire:model="qty" type="number" class="form-control">
#error('qty') <small class="text-danger">{{ $message }}</small> #enderror
</div>
<div class="form-group">
<label>Price</label>
<input wire:model="price" type="number" class="form-control">
#error('price') <small class="text-danger">{{ $message }}</small> #enderror
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Submit Product</button>
</div>
</form>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<h3>{{ $name }}</h3>
<h3>{{ $image }}</h3>
<h3>{{ $description }}</h3>
<h3>{{ $qty }}</h3>
<h3>{{ $price }}</h3>
</div>
</div>
</div>
</div>
use $this->image->extension() or \File::extension($this->image);
instead of $this->extensionin your code
$imageName = md5($this->image.microtime().'.'. $this->extension());
extension() is a method of FIle class thus needs a instance of Symfony\Component\HttpFoundation\File\UploadedFile class

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

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

How to insert values to table 'users' in laravel 5.2?

I want to insert employee details username,area to the table 'users'.
I have the following codes of CreateEmployeeController and
createemployee.blade.php view file.
When I click on the menu Create Employee is will shows the following error
QueryException in Connection.php line 662:
SQLSTATE[42000]: Syntax error or access violation: 1066 Table/alias: 'users' non unique (SQL: select * from users inner join users on users.id = users.users_id where users.deleted_at is null)
Controller file :
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\AdminController;
use App\CreateEmployee;
use App\Employee;
use App\Users;
class CreateEmployeeController extends AdminController
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function addemployee()
{
$employee = CreateEmployee::all();
$employee =CreateEmployee::join('users','users.id','=','users.users_id')->get();
return view('app.admin.employee.employee',compact('employee','users'));
}
public function employeesave(Request $request)
{
$title = 'Add Employee';
$employee = new Employee();
$employee->name=$request->employee_name;
$employee ->area = $request->area;
$employee->save();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'employee created successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function updateemployee(Request $request)
{
Employee::where('id',$request->id)->update(array('name'=>$request->employee_name,'area'=>$request->area));
Session::flash('flash_notification', array('level' => 'success', 'message' => 'shop details updated successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee',array('id' => $request->id));
}
public function editemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.editemployee',compact('employee'));
}
public function deleteemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.delete',compact('employee'));
}
public function deleteconfirms($id)
{
$employee = Employee::where('id',$id)->delete();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'customer deleted successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function destroy($id)
{
//
}
}
//view file
#extends('app.admin.layouts.default')
{{-- Web site Title --}}
#section('title') {{{ trans('site/user.register') }}} :: #parent #stop
#section ('styles')
#parent
<style type="text/css">
</style>
#stop
{{-- Content --}}
#section('main')
#include('utils.vendor.flash.message')
<div class="row">
<div class="page-header">
<h2>Add Employee</h2>
</div>
</div>
<div class="container-fluid">
<div class="row">
#include('utils.errors.list')
<form class="form-horizontal" role="form" method="POST" action="{{ URL::to('admin/addemployee') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Employee Name</label>
<div class="col-md-2">
<input type="text" class="form-control" name="employee_name"
required>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="religion">Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" data-parsley-trigger="change" data-parsley-required="true" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('cpassword', '<label class="control-label" for="cpassword">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="caste">Confirm Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Confirm Password" name="password_confirmation" id="password_confirmation" data-parsley-trigger="change" data-parsley-required="true" data-parsley-equalto="#password" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('password_confirmation', '<label class="control-label" for="password_confirmation">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Area</label>
<div class="col-md-2">
<input type="text" class="form-control" name="area"
required placeholder="Area">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-md-offset-2">
<button type="submit" class="btn btn-primary">
Add
</button>
</div>
</div>
</form>
</div>
</div>
<div class="invoice-content">
<div class="table-responsive">
<div class="col-md-offset-2">
<table class="table table-invoice">
<thead>
<tr>
<th>Employee Name</th>
<th>Area</th>
</tr>
</thead>
</div>
</div>
<tbody>
#foreach($addemployee as $employee)
<tr>
<td>{{$employee->employee_name}}</td>
<td>{{$employee->area}}</td>
<td>
Edit
<a onclick="return confirm('Are you Sure you want to do this Action!'); style.backgroundColor='#84DFC1'; " href="employee/delete/{{$employee->id}}">delete</a>
</td>
</tr>
#endforeach
#if(!count($employee))
<tr><td>NO data found </td></tr>
#endif
</tbody>
</tbody>
</table>
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
</div>
</div>
#endsection
I can't get the full idea about your problem, but as upto me I understand that - You are using same table/column names in your join statement, you can do this as:
$employee = CreateEmployee::join('users', 'create_employees.id','=', 'users.employee_id')->get();
Hope this helps!

Resources