My model always give empty even I have data in database Laravel 5 - laravel

UPDATE
I just found the problem here, it is typo at $instID = $request->insititution;
It should be $instID = $request->institution;
Thanks for all your helps..
UPDATE
I trying to insert to CRConfigDetail Model / table, but first I need to get my CRConfigID from CRConfig Model / Table with specific rules. So I can get the CRConfigID and put it to CRConfigDetail column.
But every time I trying to retrieve, it always give empty data even I already have data at my database. In other Controller I can retrieve data with similar rules.
Am I do something wrong with logic? Because I don't see any errors.
Here is my HTML / form:
<form action="doInsertSCC" method="POST" enctype="multipart/form-data" id="scheduleDetailForm">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="fos">Field of Study</label>
<select name="fos" class="form-control" id="fos">
</select>
</div>
<div class="form-group">
<label for="scc">Lecturer's ID - Name</label>
<select name="scc" class="form-control" id="scc">
</select>
</div>
<button type="submit" class="btn btn-default">Assign SCC</button>
<div id="search" class="btn btn-default">Search</div>
</form>
Here is my Route to access my Controller
Route::post('/doInsertSCC', "ScheduleController#insertSCC");
And here is my ScheduleController
public function insertSCC(Request $request){
$this->validate($request, [
'scc' => 'required'
]);
$instID = $request->insititution;
$acadID = $request->acadCareer;
$termID = $request->period;
$depID = $request->department;
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
if( !empty($crConfig) ){
foreach ($crConfig as $cr) {
$crConfigID = $cr->CRConfigID;
}
$schedule = new CRConfigDetail;
$schedule->status = 'Pending';
$schedule->numRevision = 0;
$schedule->FOSID = $request->fos;
$schedule->SCC = $request->scc;
$schedule->CRConfigID = $crConfigID;
$schedule->save();
return redirect("AssignSCC")->with('status', 'Add SCC success!');
}else{
return redirect("AssignSCC")->with('status', 'Add schedule first!');
}
}
I already check my rules data are match with my CRConfig table's data (using console.log()
Everytime I submit this form, I will do the "else" and redirect with "Add schedule first!" message.

Actually, it does accept an array, but the array should be formatted as such..
$rule = [
['institutionID', '=', $instID],
['acadCareerID', '=', $acadID],
['termID', '=', $termID],
['departmentID', '=', $depID]
];
Source: https://laravel.com/docs/5.4/queries#where-clauses

use the below one
$crConfig = CRConfig::where('institutionID' , $instID)
->where('acadCareerID' , $acadID)
->where('termID', $termID)
->where('departmentID', $depID)
->first();
instead of
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
You can check the query built at the backend by getting the query log, for this you have to enable the query log before the query gets built and get the query log after the query gets built both query log methods belongs to DB facade
\DB::enableQueryLog();
\DB::getQueryLog();

Related

Eloquent update doesn't work in Laravel 6

I'm trying to update a field after submitting in the following form:
<form action="{{ route("comments.update") }}" method="post">
#csrf
<input type="hidden" name="commentIDToEdit" id="commentID">
<div class="md-form mb-5">
<i class="fas fa-comment"></i>
<label for="toEditComment"></label>
<textarea name="toEditCommentary" id="toEditComment" cols="3" rows="5" style="resize: none"
class="form-control"></textarea>
</div>
<div class="modal-footer d-flex justify-content-center">
<button type="submit" class="btn btn-default">Modificar</button>
</div>
</form>
I have the CommentsController, where I process the data from the form. Here is the code:
public function updateComment()
{
request()->validate([
"toEditCommentary" => "min:10|max:500"
]);
if (Session::has("username") && getWarningCount(User::whereUsername(session("username"))->value("email")) > 0) {
Caveat::where("commentID", request("commentIDtoEdit"))
->update(["updatedComment" => request("toEditCommentary")]);
} else {
die("No se cumple la condiciĆ³n");
}
if (Comment::where("commentID", request("commentIDToEdit"))->exists()) {
Comment::where("commentID", request("commentIDToEdit"))
->update(["commentary" => request("toEditCommentary")]);
}
return back();
}
Curiosly, the comment is updated in his table, but not the warning. I was thinking in the fillable property in the model, but I don't have it, instead this, I have the following code:
protected $guarded = [];
const UPDATED_AT = null;
const CREATED_AT = null;
Your hidden input is named commentIDToEdit, but in the Controller you fetch the Caveat using request("commentIDtoEdit") (different case).
What you wrote:
Caveat::where("commentID", request("commentIDtoEdit"))
What you should have done: (note the different casing)
Caveat::where("commentID", request("commentIDToEdit"))
This is because in the view, the input name is commentIDToEdit, not commentIDtoEdit.

Getting value from (select2) to another filed input laravel

I have select2 field input. After using select2 its will showing new column and data from this input selected.
I have referenced like this link. So after I using select2, this value will show in a new column. But I don't know how to catch this data. I am using Laravel and this is my controller and view:
Controller
$collection = Alat::get(['nama_alat','no_inventaris','status_alat','id']);
foreach ($collection as $item) {
$inven[$item->id] = $item->no_inventaris.'-'.$item->nama_alat;
}
This is will shown in columns no_inventaris and nama_alat in the select2. But in the $collection, I have status_alat, this data is what I need to display in another column.
This is my view:
// This is form Select2
<div class="form-group">
<label>Pilih Inventaris</label>
<select class="form-control select2bs4" name="alat_id" id="alat_id" style="width: 100%;" aria-hidden="true" onchange="Show()">
<option value=""></option>
#foreach($inven as $id => $item )
<option value="{{ $id }}">{{ $item }} </option>
#endforeach
</select>
</div>
// This is form what i need to show another value
<div class="form-group" id="divid" style="display:none">
<label class="control-label" for="title">Kondisi Alat Sekarang:</label>
<input type="text" name="" class="form-control" id="value" data-error="Please enter title." readonly />
<div class="help-block with-errors"></div>
</div>
Here's my Javascript:
<script>
function Show()
{
var fieldValue = $('#alat_id').val();
if(fieldValue == "")
{
document.getElementById("divid").style.display = 'none';
}
else{
document.getElementById("divid").style.display = 'inline'
}
}
</script>
This data I need to catch in the controller $collection as status_alat. How can I catch this data after input the select2 and showing in the new column? This column is shown, but I don't know how to catch this data. Sorry for my bad English
The best solution should be using ajax, it is quite complicated to access a PHP collection variable inside a javascript. If it were me, I would create a function that fetch the selected select2 data by its id. This is my example code :
<script>
function select2Changed()
{
var alat_id = $('#alat_id').val();
if(fieldValue == ""){
document.getElementById("divid").style.display = 'none';
} else{
document.getElementById("divid").style.display = 'inline';
$.ajax({url: "[url]/get-alat-status/"+alat_id, success: function(result){
document.getElementById("value").value = result;
}});
}
}
</script>

I Cannot able to pass the id in route file in laravel

I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:
If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id
Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.
Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php

Trying to load checkbox results into iFrame in CodeIgniter

I am attempting to learn CodeIgniter. I want to send checkbox values from my view (index.php), via my controller (also called index.php confusingly, but that is what it is called at my company i work at, is this a good idea?), to an iFrame (which has a file called results.php) within my view. So far I get an array on view but only keys being shown - no values from checkboxes - like this:
Array ( [resultsAreaCode] => [resultsNumberType] => [resultsOrder] => [fred] => DAVE [sheep] => cow ) TEST
Here is my view with checkboxes and target iframe, note that one checkbox is populated by PHP/SQL:
<form id="numberOrderForm" action="index/localNumberResults" method="post" enctype='multipart/form-data'>
<div class="wrappers" id="multi-select1Wrapper">
<h2>Area Code</h2>
<select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
?>
</select>
</div>
<div class="wrappers" id="multi-select2Wrapper">
<h2>Number Type</h2>
<select class="dropDownMenus" id="multi-select2" name="multi_select2[]" multiple="multiple">
<option class="menuoption2" name="package" value="gold">Gold</option>
<option class="menuoption2" name="package" value="silver">Silver</option>
<option class="menuoption2" name="package" value="bronze">Bronze</option>
</select>
</div>
<div class="wrappers" id="multi-select3Wrapper">
<h2>Order</h2>
<select class="dropDownMenus" id="multi-select3" name="multi_select3[]" >
<option class="menuoption3" name="order" value="sequential">Sequential</option>
<option class="menuoption3" name="order" value="random">Random</option>
</select>
</div>
<input type="submit" value="Submit">
</form>
<div id="resultsTableWrapper">
<iframe id="resultsTable" src="http://my-company.com/localNumberResults" width="100%"></iframe>
</div>
This is within my controller (this I have been told by my tutor is correct though):
class Index extends CI_Controller { // this is my controller!
public function localNumberResults()
{
$data['formdata']= array(
'resultsAreaCode' => $this->input->post("menuAreaCode"),
'resultsNumberType' => $this->input->post("package"),
'resultsOrder' => $this->input->post("order"),
'fred' => 'DAVE',
'sheep' => 'cow'
);
$data['contentlocation'] = 'system/results';
$this->load->view('system/template', $data);
}
}
Can anyone point me in the right direction where i am going wrong? :-)

Laravel 4 - Many to Many - pivot table not updating

I get no obvious errors when adding a new job to my database.
My industry job goes into the jobs table but the relationship with divisions in my join table goes nowhere. I just can't see where I'm going wrong
JOIN TABLE
division_industryjob
division_id
industryjob_id
divisions
id
division_name
industryjobs
id
job_title
MODELS
Division.php
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
/**
* Industry Jobs relationship
*/
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function divisions()
{
return $this->belongsToMany('Division');
}
}
ROUTES
Route::get('industry-jobs/add', 'AdminController#getCreateIndustryJob');
Route::post('industry-jobs/add', 'AdminController#postCreateIndustryJob')
CONTROLLER
// Create Industry - Get (empty form - new entry)
public function getCreateIndustryJob()
{
View::share('page_title', 'Create a new Industry Job Role');
View::share('sub_page_title', 'Ex: Mechanical Technician');
return View::make('admin/industry-jobs/create');
}
// Create Industry - Post
public function postCreateIndustryJob()
{
//validate user input
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::to('/admin/industry-jobs/add')->withErrors($validation);
} else {
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
if (isset($input['divisions'])) {
foreach ($input['divisions'] as $divId) {
$div = Division::find($divId);
$industryjob->divisions()->save($div);
}
}
$industryjob->save();
return Redirect::to('/admin/industry-jobs')->with('message', 'Industry Job created successfully');
}
}
FORM
<form class="form-horizontal" method="post" autocomplete="off">
<!-- Industry Job Title -->
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Industry Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="" />
</div>
</div>
<!-- ./ Industry Job Title -->
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Division</label>
<div class="col-md-10">
<select name="divisions[]" id="divisions" size="6" class="form-control" multiple>
#foreach (Division::all() as $division)
<option value="{{ $division->id }}" >{{ $division->division_name }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Create Job</button>
</div>
</div>
<!-- ./ form actions -->
</form>
You are saving the Parent model afterwards so it's not working. Save the Parent model before you save the Child Model, so it should be something like this:
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
Then save the related models using sync because it's many-to-many relationship and those related models are already created and available in the database:
if (isset($input['divisions'])) {
// Pass the array of ids to sync method
$industryjob->divisions()->sync($input['divisions']);
}
If you use the foreach loop then you may use something like this;
foreach ($input['divisions'] as $divId) {
$industryjob->divisions()->attach($divId);
}
Check more about inserting related models on Laravel website.

Resources