Laravel - using username instead id from other table - sql-server

I'm trying to get nickname from user table to replace nik in media_order which is usen to shown in my datatable, as for now the media_order in my datatable are still showing order that created based on their nik like this :
and here is my users table :
so, as you can see i'm trying to use the nickname to shown in my datatable, instead of their nik, and here is my controller.php :
public function index(Request $request)
{
if ($request->ajax()) {
if(auth()->user()->is_admin){
$data = MediaOrder::get();
}elseif(auth()->user()->group_id){
$data = MediaOrder::memberOf(auth()->user()->group_id)->get();
}else{
$data = MediaOrder::get();
}
return DataTables::of($data)
->addIndexColumn()
->addColumn('action',function($row){
$btn = '<a style="margin:5px" href="javascript:void(0)" id="viewMediaOrder" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="View" class="edit btn btn-primary btn-sm button1 viewMediaOrder" value="{{ csrf_token() }}"><i class="fa fa-eye mr-1"></i>View</a>';
if($row->isdisabled == 0 && !auth()->user()->is_traffic){
$btn = $btn.'<a style="margin:5px" href="javascript:void(0)" id="editMediaOrder" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-warning btn-sm button1 editMediaOrder" value="{{ csrf_token() }}"><i class="fa fa-pencil mr-1"></i>Edit</a>
<a style="margin:5px" href="javascript:void(0)" data-toggle="tooltip" id="disableMediaOrder" data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm button1 disableMediaOrder" value="{{ csrf_token() }}"><i class="fa fa-power-off mr-1"></i>Disable</a>';
}
return $btn;
})
->addColumn('created_by', function($row){
return $row->userss->nickname;
})
->editColumn('is_traffic_viewed', function($row){
if(($row->is_traffic_viewed == 0 && auth()->user()->is_traffic) && $row->isdisabled == 0){
$combo = '<input data-id="'.$row->id.'" type="checkbox" class="checkedTraffic">Check</input>';
return $combo;
}elseif($row->is_traffic_viewed == 0){
$row = "Unchecked";
return $row;
}elseif($row->is_traffic_viewed == 1){
$row = "Checked";
return $row;
}elseif(!auth()->user()->is_traffic){
$row = $row->is_traffic_viewed;
return $row;
}
})
->editColumn('attachment_name',function($row){
$data = json_decode($row['attachment_name'], true);
$res = ''; $count = count($data);
foreach ($data as $value){
$res .= $value;
if($count > 1){
$res .= ', ';
}
$count--;
}
return $res;
})
->rawColumns(['action','is_traffic_viewed'])
->make(true);
} else {
\Meta::set('title', 'Media Order');
$groups = Group::all();
$media_order = DB::table('media_order')->get();
$moo = MediaOrder::get();
$selected = auth()->user()->group_id;
$mediaOrder = MediaOrder::all()->first();
$users = User::orderBy('name', 'asc')->get();
return view('media-order.index')->with(compact('users','moo','groups','selected','mediaOrder'));
}
}
here is my UserModel :
public function media()
{
return $this->hasMany(MediaOrder::class);
}
here is my mediaOrder model :
public function userss()
{
return $this->belongsToMany(User::class, 'id')->get();
}
so far, i have tried to edit my function index like this :
$data= MediaOrder::with('userss')->select('media_order.*')->get();
and adding the editColumn for replace nik as nickname like this :
->addColumn('created_by', function($row){
return $row->userss->nickname;
})
but ended up having error an SQL error like this :
LOG.error: SQLSTATE[42S02]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Invalid object name 'id'. (SQL: select [users].*, [id].[media_order_id] as [pivot_media_order_id], [id].[user_id] as [pivot_user_id] from [users] inner join [id] on [users].[id] = [id].[user_id]) {"userId":"100","exception":{"errorInfo":["42S02",208,"[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Invalid object name 'id'."]}
Anyone maybe have an alternative way or maybe solution for this?, any help is really appreciated. Thank you!

The second parameter of a belongsToMany() method is the intermediate table, not the column which provides the function key.
The giveaway is in your error message where it's looking for :
[id].[media_order_id]
as 'id' is unlikely to be the name of a table. Sure enough, your userss() method defines 'id' in the place where Laravel is expecting to find the name of the table.
public function userss() {
return $this->belongsToMany(User::class, 'id')->get();
}

Related

Laravel: Updating multiple files in array

I was able to store and save multiple files in the array into the database, as well as updating the form data. However, the problem now is it returns this error when I update the form without updating the file.
count(): Parameter must be an array or an object that implements Countable
Does anyone know what should I do for my update function or value in my blade file so that it won't delete the file elements?
--------------------------------------------- UPDATED ---------------------------------------------
public function update(Request $request, $id)
{
$data = $request->all();
$data = $this->saveEmptyData($data);
$c = Document::find($id);
$fileData = [];
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('storage/documents');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc = json_encode($fileData);
$c->file = $doc;
$c->name = $request->name;
$c->price = $request->price;
$c->publish = $request->publish;
}
//else {
// redirect()->back()->with('errors', 'File is required!');
//}
$c->save();
return redirect()->route('product.index')->with('success', 'Document updated successfully');
}
Blade
<form method="POST" action="{{ route('document.update', $doc) }}" enctype="multipart/form-data">
<fieldset>
....
<div class="form-group">
<label>Document</label>
<div class="input-group-append">
<label for="upload_file">Upload</label>
<input id="upload_file" type="file" name="file[]" value="{{ isset($doc) ? $doc['file'] : '' }}" multiple>
</div>
</div>
</fieldset>
</form>
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc= json_encode($fileData); //replace $doc['file'] with $doc
$c->file=$doc;
}
$c->save();
//not required to declare $fileData ;
enctype="multipart/form-data" in form tag
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc['file'] = json_encode($fileData);
}

implode function not working in codeigniter

I want to store a checkbox array value by using implode function.when i stored,the database table value as Array (not a integer value show only array)
This is my view file:
<div class="col-sm-12">
<div>
<label class="form-control-label">Select Asset Type</label><br>
<div class="border-checkbox-section">
<div class="border-checkbox-group border-checkbox-group-primary">
<?php $b=0; foreach($assettype as $assettype_info){ $b++;?>
<input type="checkbox" name="assettype_name[]" class="border-checkbox" value="<?php echo $assettype_info->assettype_name; ?>" id="checkbox<?php echo $b;?>">
<label class="border-checkbox-label" for="checkbox<?php echo $b;?>"><?php echo $assettype_info->assettype_name; ?></label>
<?php } ?>
</div>
</div>
</div>
My Controller:
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(", ", $_POST['assettype_name']) ;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}
My Model :
Public function insertrecord($Table)
{
$Inputs=$_POST;
$Inputs["joinon"]=date("Y-m-d");
$Keys=array();
$Values=array();
foreach($Inputs as $Inp_key=>$inp_value)
{
if($Inp_key!="submit" && $Inp_key!="PHPSESSID")
{
$Keys[]= $Inp_key;
$Values[]= "'".$inp_value."'";
}
}
$keys=implode(',',$Keys);
$values=implode(',',$Values);
$qry="insert into ".$Table."(".$keys.") values(".$values.")";
$ack=$this->db->query($qry);
if($ack) return true; else return false;
}
I expected to store a array value as id with comma
DB shows as :
Db shows as
modified in controller to get the answer.
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(",",$_POST['assettype_name']) ;
$_POST['assettype_name'] = $assettype_name;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}

Laravel insert dynamic inputs into database

I'm trying to save dynamic inputs in multiple rows in my database.
This is a part of my form which are payments and dates.
<tr>
<td class="col-md-2">
{{Form::text('pay[]', '', ['class' => 'form-control number', 'placeholder' => ''])}}
</td>
<td class="col-md-2">
{{Form::text('payDate[]', '', ['class' => 'form-control pDate', 'placeholder' => ''])}}
</td>
<td class="col-md-2"><a class="deleteRow"></a>
</td>
</tr>
My JS code that add inputs dynamically:
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" id="field_2" class="form-control" name="pay[]" /></td>';
cols += '<td><input type="text" class="form-control pDate" name="payDate[]" /></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
And this is my Controller:
$input = $request->all();
for($i=0; $i<= count($input['pay']); $i++) {
$payment = new Payment;
$payment->file = $file;
$prePayment = str_replace(',', '', $request->input('pay'));
$payment->payment = $prePayment;
$payment->paymentDate = $request->input('payDate');
$payment->save();
}
Could you please help me to fix this issue.
At the moment I get this error:
Array to string conversion (SQL: insert into payments (file, payment, paymentDate, updated_at, created_at) values ....
May be $request->input('pay') this line causing the problem as you are trying to fetch whole array here, instead you should fetch single object.
$input = $request->all();
$pays = $request->input('pay');
$paymentDates = $request->input('payDate');
for($i=0; $i< count($input['pay']); $i++) {
$payment = new Payment;
$payment->file = $file;
$prePayment = $pays[$i];
$payment->payment = str_replace(',','',$prePayment);
$payment->paymentDate = $paymentDates[$i];
$payment->save();
}

how to upload image to folder and path ot db in cakephp controller

i have written code in controller to move the uploaded file to folder ,but it was not working ,my code is
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a, '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
i think this line 'if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){ ... } was not working ,through this code i am able to store the '0 in my database i.e else part of the code.
how to move the uploaded image to folder and path to my database field..plz help me any one...!
my script code is
function addAdminList(){
var branchId = $('#branchId').val();
var branchName = $('#branchName').val();
var curiculumName = $('#curiculumName').val();
var owner = $('#owner').val();
var startdate = $('#startdate').val();
var phone = $('#phone').val();
var desc = $('#desc').val();
var address = $('#address').val();
var timings = $('#timings').val();
var image = $('#image').val();
if(!$("#addClsGrpFrm").validationEngine('validate')){
return false;
}
$('.overlay').show();
$.ajax({
url : '<?php echo BASE_PATH; ?>adminAjax/addAdminList',
type : 'POST',
data : {
branchId : branchId,
branchName : branchName,
curiculumName : curiculumName,
owner : owner,
startdate : startdate,
phone : phone,
desc : desc,
address : address,
timings : timings,
image : image
},
success : function(res){
$('.overlay').hide();
if(res == 0){
}
parent.$.colorbox.close();
oTable.fnDraw();
return false;
},
error : function(res){
alert('Server Error Occurred');
}
});
}
my form is
<form id="addClsGrpFrm" method="post" action="#" onsubmit="return disableFrmSubmit()">
<div class="flash_msg"><?php echo $this->Session->flash(); ?></div>
<input type="hidden" name="data[branch][id]" readonly id="branchId" value="0">
<div class="login-form">
<label>Shop Image</label>
<input type="file" id="image" data-prompt-position="topLeft:200" name="data[branch][image]" placeholder="" class="validate[required]" />
.....
</div>
<div class="login-form">
<input type="button" onclick="addAdminList()" class="login-btn" value="Submit">
</div>
<div class="clear"></div>
</form>
Some suggestions while submitting your form :
Use FormData when submitting your form rather than appending them one by one.
The extension extraction process that you are using in your controller may not save some files with "." in their filename.
I have created a test form for your knowledge.This is the form:
<form id="testForm" method="post" action="<?php echo 'http://localhost/blog/users/test'; ?>">
<input type="file" name="image" id="image">
<input type="submit" value="Submit">
</form>
You can use FormData like so:
$('#testForm').on('submit', function(event) {
event.preventDefault();
var form_data = new FormData($(this)[0]); // this will get all your form's inputs
$.ajax({
url:"<?php echo 'http://localhost/blog/users/test.json'; ?>", // you can use your form action URL here
type:'POST',
data:form_data,
processData: false,
contentType: false
});
});
and finally in your controller:
public function test() {
if ($this->request->is('post')) {
if (!empty($this->request->data['image']['tmp_name']) && is_uploaded_file($this->request->data['image']['tmp_name'])) {
$filename = basename($this->request->data['image']['name']);
$imagePath = WWW_ROOT . DS . 'documents' . DS . $filename; // save the file where you wish
move_uploaded_file(
$this->request->data['image']['tmp_name'],
$imagePath // save $imagePath in your database
);
}
}
}
You can use $imagePath to save in your database and as for your file extension process you can use this function as it will get the filetype even if the filename has a "dot" in it :
public function findFileTypeAndName($filename)
{
$split_point = '.';
$parts = explode($split_point, $filename);
$last = array_pop($parts);
$fileNameAndType = array(implode($split_point, $parts), $last);
return $fileNameAndType;
}
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a['tmp_name'], WWW_ROOT . '/img/uploads/users/' . basename($a['name']))){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
The issue is just that you tried to pass the image array to strrchr($a) instead of strrchr($a['name']) at this point:
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
Then you also tried to pass $a which is an array into move_uploaded_file($a,...).
Check my corrections for that part of the code...

CodeIgniter Dropdown menu fetching data from database column

I am having a problem. Please let me know if there is a solution. I am new to codeigniter therefore, sorry in advance if there is a silly one!
I am trying to fetch data from a database. Table name is fw_main_cat which have fields (cat_id, cat_parent_id, cat_level, cat_title, cat_menu_order and cat_status). cat_id is unique.
I want a dropdown menu (in view) to take all the data of a column cat_title through cat_level (which are int). So, how can I do?
Here is my code which I have tried so far.
This is Model :
public function cat_level_one($cat_level)
{
$sql = "Select * from fw_main_cat Where cat_level=? ";
$result = $this->db->query($sql, $cat_level);
if($result->num_rows() > 0)
{
return $result->result_array();
}
else { return false;
}
}
This is Controller :
public function getcategory()
{
if ($this->session->userdata('session_status'))
{
$cat_level_one = $this->admin_cat_model->cat_level_one($cat_level);
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
This is View (dropdown menu):
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="<?php if(isset ($cat_level_one) && $cat_level_one != ''){ foreach ($cat_level_one as $cat_one){ echo $cat_one->cat_id; } } ?>"
selected="selected">------------Select Category------------</option>
Thanks! for the consideration.
Updated code -
// in model
function cat_level_one($cat_level)
{
$this->db->where('cat_level',$cat_level);
$q = $this->db->get('fw_main_cat');
$data = $q->result_array();
return $data;
}
//controller function
public function getcategory()
{
**if ($this->session->userdata('session_status'))
{
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);**
//Where this post data comes from??
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
//in view
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="">-- Select Category --</option>
<?php foreach($cat_level_one as $cat_one){ ?>
<option value="<?php echo $cat_one->cat_id; ?>"><?php echo $cat_one->cat_title; ?></option>
<?php } ?>
</select>
</li>

Resources