i have problem working with laravel request->ajax() its always return false. so the if statement is not working on what function is to be called. Im using datatables to render the table.
this code i have is not working properply
ContactController.php
public function index()
{
$type = request()->get('type');
$types = ['supplier', 'customer'];
if (empty($type) || !in_array($type, $types)) {
return redirect()->back();
}
if (request()->ajax()) {
if ($type == 'supplier') {
return $this->indexSupplier();
} elseif ($type == 'customer') {
return $this->indexCustomer();
} else {
die("Not Found");
}
}
$reward_enabled = (request()->session()->get('business.enable_rp') == 1 && in_array($type, ['customer'])) ? true : false;
return view('contact.index')
->with(compact('type', 'reward_enabled'));
}
private function indexSupplier()
{
if (!auth()->user()->can('supplier.view') && !auth()->user()->can('supplier.view_own')) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
$contact = $this->contactUtil->getContactQuery($business_id, 'supplier');
if (request()->has('has_purchase_due')) {
$contact->havingRaw('(total_purchase - purchase_paid) > 0');
}
if (request()->has('has_purchase_return')) {
$contact->havingRaw('total_purchase_return > 0');
}
if (request()->has('has_advance_balance')) {
$contact->where('balance', '>', 0);
}
if (request()->has('has_opening_balance')) {
$contact->havingRaw('opening_balance > 0');
}
return Datatables::of($contact)
...
}
private function indexCustomer()
{
if (!auth()->user()->can('customer.view') && !auth()->user()->can('customer.view_own')) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
$is_admin = $this->contactUtil->is_admin(auth()->user());
$query = $this->contactUtil->getContactQuery($business_id, 'customer');
return Datatables::of($query)
...
}
this is the sidebarblade that links to the controller.
if (auth()->user()->can('supplier.view') || auth()->user()->can('supplier.view_own')) {
$sub->url(action('ContactController#index', ['type' => 'supplier']),__('report.supplier'),
['icon' => 'fa fas fa-star', 'active' => request()->input('type') == 'upplier']);
}
if (auth()->user()->can('customer.view') || auth()->user()->can('customer.view_own')) {
$sub->url(action('ContactController#index', ['type' => 'customer']),__('report.customer'),
['icon' => 'fa fas fa-star', 'active' => request()->input('type') == 'customer']);
$sub->url(action('CustomerGroupController#index'),__('lang_v1.customer_groups'),
['icon' => 'fa fas fa-users', 'active' => request()->segment(1) == 'customer-group']);
}
Related
i have a form whereby on updating the data and storing it to the database it shows a success message.if one of the inputs isn't filled it shows an error.am getting a bug whereby when i want to re-update the data and i open the form with the existing inputs when i click save the data should just redirect back to the previous page and not show the success message as the data hasnt being updated.how can i achieve this,am looking for a logic here fellow devs..here is my update function code
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$systemid = $request->systemid;
$product_details = product::where('systemid', $systemid)->first();
$changed = false;
if ($request->has('product_name')) {
if ($product_details->name != $request->product_name) {
$product_details->name = $request->product_name;
$changed = true;
}
}
if ($request->has('category')) {
if ($product_details->prdcategory_id != $request->category) {
$product_details->prdcategory_id = $request->category;
$changed = true;
}
}
if ($request->has('subcategory')) {
if ($product_details->prdsubcategory_id != $request->subcategory) {
$product_details->prdsubcategory_id = $request->subcategory;
$changed = true;
}
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if($voucher->subcategory_id != $request->subcategory){
$voucher->subcategory_id = $request->subcategory;
$voucher->save();
$changed = true;
}
}
}
if ($request->has('prdcategory')) {
if ($product_details->prdprdcategory_id != $request->prdcategory) {
$product_details->prdprdcategory_id = $request->prdcategory;
$changed = true;
}
}
if ($request->has('prdbrand')) {
if ($product_details->brand_id != $request->prdbrand) {
$product_details->brand_id = $request->prdbrand;
$changed = true;
}
}
if ($request->has('description')) {
if ($product_details->description != $request->description) {
$product_details->description = $request->description;
$changed = true;
}
}
if ($changed == true || true) {
$product_details->save();
$msg = "Product information updated successfully";
$data = view('layouts.dialog', compact('msg'));
//i have added this code but it doesnt work
} else if($changed == false) {
return back();
$data = '';
}
}
return $data;
}
my laravel project version is 5.8
The following line will always evaluate to True
$changed == true || true
And you have a catch statement missing at the end so I had to add it.
And I advise you to simply get the dirty version of $product_details.
You can use $product_details->isDirty() // boolean.
Or even better way is to use $product_details->wasChanged() // boolean
Here is the code after some tweaks:
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception('validation_error', 19);
}
$systemid = $request->systemid;
$product_details = Product::where('systemid', $systemid)->first();
$changed = false;
// Looping for all inputs:
$fieldsToCheck = [
'name' => 'product_name',
'prdcategory_id' => 'category',
'prdsubcategory_id' => 'subcategory',
'prdprdcategory_id' => 'prdcategory',
'brand_id' => 'prdbrand',
'description' => 'description',
];
foreach ($fieldsToCheck as $productColumnName => $requestFieldName) {
$requestInput = $request->{$requestFieldName};
if ($request->has($requestFieldName)) {
if ($product_details->$productColumnName != $requestInput) {
$product_details->$productColumnName = $requestInput;
$changed = true;
}
}
// Exception for Sub Category to check for the voucher.
if ($requestFieldName == 'subcategory') {
$this->handleVoucher($requestInput);
}
}
// here I advise you to simply get the dirty version of $product_details
// you can use $product_details->isDirty() // boolean
// or even better use $product_details->wasChanged() // boolean
if ($changed) {
$product_details->save();
$msg = 'Product information updated successfully';
$data = view('layouts.dialog', compact('msg'));
} else {
return back();
// Todo Mo: No need for this line so I commented it out.
//$data = '';
}
} catch (\Exception $e) {
dd($e->getMessage(), 'Oops, error occurred');
}
return $data;
}
private function handleVoucher($product_details, $subcategory)
{
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if ($voucher->subcategory_id != $subcategory) {
$voucher->subcategory_id = $subcategory;
$voucher->save();
}
}
}
I want to update actualCost
ProposalExpenses::where('EXPENSE_ID', '=', $request->id)
->update(['ACTUAL_EXPENSES' => $request->actualCost]);
//this my function
public function ProgrameLogExpUploadFiles(Request $request, $proposal_id) {
$officer = officer::where('USER_LOGIN_LOGIN_ID', '=', Auth::user()->LOGIN_ID)->first();
if (isset($request->id)) {
ProposalExpenses::where('EXPENSE_ID', '=', $request->id)
->update(['ACTUAL_EXPENSES' => $request->actualCost]);
if ($request->updated == "true" && $request->balance <= 0) {
$old_files_db = \App\model\programme_proposal\ProgrammeExpenseFileUpload::where([
'PROPOSAL_ID'=>$proposal_id,
'EXPENCE_ID'=>$request->id
])->get();
\App\model\programme_proposal\ProgrammeExpenseFileUpload::where([
'PROPOSAL_ID'=>$proposal_id,
'EXPENCE_ID'=>$request->id
])->delete();
if(isset($old_files_db)){
foreach ($old_files_db as $file) {
try {
\Illuminate\Support\Facades\Storage::delete("programme_expenses/" . $file->STORAGE_FILE_NAME);
} catch (\Exception $e) {
}
}
}
foreach ($request->file as $file) {
$upload_success = $file->store('programme_expenses');
if ($upload_success) {
\App\model\programme_proposal\ProgrammeExpenseFileUpload::create([
'STORAGE_FILE_NAME' => str_replace("programme_expenses/", "", $upload_success),
'REAL_NAME' => $file->getClientOriginalName(),
'UPLOADED_DATE' => \Illuminate\Support\Carbon::now(),
'UPLOADED_BY_STAFF_NIC' => $officer->NIC,
'PROPOSAL_ID' => $proposal_id,
'EXPENCE_ID' => $request->id
]);
}
}
}
if ($request->updated == "false" && $request->balance > 0) {
$old_files_db = \App\model\programme_proposal\ProgrammeExpenseFileUpload::where(['PROPOSAL_ID'=>$proposal_id,'EXPENCE_ID'=>$request->id])->get();
\App\model\programme_proposal\ProgrammeExpenseFileUpload::where(['PROPOSAL_ID'=>$proposal_id,'EXPENCE_ID'=>$request->id])->delete();
if(isset($old_files_db)){
foreach ($old_files_db as $file) {
try {
\Illuminate\Support\Facades\Storage::delete("programme_expenses/" . $file->STORAGE_FILE_NAME);
} catch (\Exception $e) {
}
}
}
}
}
}
public function shirts($type = '') {
{
if ($type == 'glass') {
$shirt = Product::where('category_id', '1') - > get();
}
elseif($type == 'ic') {
$shirt = Product::where('category_id', '2') - > get();
}
elseif($type == 'cover') {
$shirt = Product::where('category_id', '3') - > get();
} else {
$shirt = Product::all();
}
$products = Category::find($shirt);
return view('front.shirt', compact('products', 'shirt'));
}
}
can some one help me in minimising this Controller I don't want to use if else statement
Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$this->year_model->insert($_POST);
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
Model:
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
}
View:
<div class="text-danger">
//display error message
</div>
MY Question: How can i display model error message in view............................................................
use below updated code for your solution
Model :
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
return TRUE;
}
add_year
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$ret = $this->year_model->insert($_POST);
if(!$ret){
$this->session->set_flashdata('error_view',$ret);
}
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
in view
<?php
echo $this->session->flashdata('error_view');
?>
Use this Code
Note : please set your table and field name in is_unique function !
Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id))
{
$this->form_validation->set_rules('year_name', 'Year Name', 'required|is_unique[table_name.field_name]');
if ($this->form_validation->run() == FALSE) {
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else {
if( $this->year_model->insert($_POST)==true)
{
redirect('admin/Year');
}
}
} else
{
redirect('admin/Login');
}
}
Model
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
return true;
} else {
return false;
}
}
View File
<div class="panel-body">
<?php if(validation_errors()) { ?>
<div class="alert alert-danger"><?php echo validation_errors(); ?></div>
<?php } ?>
On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}