grocery crud rename filename on upload - codeigniter

I need to rename the file on file upload and inserting to the database.
I search for ways but i can't find the right code.
I tried to use callback but it did not work.
Here's my code:
public function home()
{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('blog_post');
$crud->set_field_upload('post_image',UPLOAD_PATH);
$crud->callback_before_upload(array($this,'_before_upload'))
$crud->callback_before_insert(array($this,'rename_img_db'));
$output = $crud->render();
$this->_example_output($output);
}
function rename_img_db($post_array)
{
if (!empty($post_array['post_image'])) {
$ext = end(explode(".",$post_array['post_image']));
$img_name = $post_array['post_image'] = mktime().".".$ext;
$post_array['post_image'] = $img_name;
}
return $post_array;
}
function _before_upload($files_to_upload,$field_info)
{
foreach($files_to_upload as $value) {
$ext = pathinfo($value['name'], PATHINFO_EXTENSION);
$rename = $value['name'];
}
$allowed_formats = array("jpg","gif","png","doc","docx","pdf");
if(in_array($ext,$allowed_formats))
{
return true;
}
else
{
return 'Wrong file format';
}
if ($rename) {
$ext1 = end(explode(".",$rename));
$img_name = $rename = mktime().".".$ext1;
$rename = $img_name;
return $rename;
}
}

I noticed a tipo in your line: $crud->callback_before_upload(array($this,'_before_upload'))
Moreover I had to do something similar and I used the callback_after_insert, then you can get the $primary_key variable and with that update the element, something like this:
$crud->callback_after_insert(array($this, 'rename_img_db'));
public function rename_img_db($post_array,$primary_key)
{
//Here goes the get and set querys with your $primary_key
}

Related

Too few arguments to function App\Awe\JsonUtility::addNewProduct(),

i am trying to create a CRUD app and am having trouble, if anyone can point me in the right direction i would be grateful, thank you.
Hi there i am having difficulty using data from the json.
i have used it here and it as worked
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}
this is my controller
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}
this is my route
Route::get('/product' , [ProductController::class, 'index'] );
how can i use this on my controller and what route should i set up to create a product
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}
This is where i am trying to type to code into.
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}
your function addNewProduct() is expecting 7 parameters when called.
you are getting this error because you cannot provide those parameters that your function is looking for.
in your code above you are passing 'products.json' which is in a string format.
lets assume that it is a JSON data. it will still fail because you are only passing 1 parameter to a function that is expecting 7 parameters.
what you could probably do is change it to
public static function addNewProduct($data)
{
// code here
}
then you can pass your JSON data and then go through each of your json using a loop.

Laravel 6 pathinfo() expects parameter 1 to be string, object given

This is where i get the error:
$data = Excel::import($path, function($reader) {})->get();
I changed the load() to import(). I want to run this code in Laravel 6, but version 3 of MaatWebsiteExcel does not support load().
I've been searching for solutions, yet i cant find any....
This is my controller:
namespace App\Http\Controllers;
use App\Contact;
use App\CsvData;
use App\Http\Requests\CsvImportRequest;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Session;
use DB;
class ImportController extends Controller
{
public function getImport()
{
return view('import');
}
function parseImport(CsvImportRequest $request)
{
$path = $request->file('csv_file')->getRealPath();
if ($request->has('header')) {
$data = Excel::import($path, function($reader) {})->get();
} else {
$data = array_map('str_getcsv', file($path));
}
if (count($data) > 0) {
if ($request->has('header')) {
$csv_header_fields = [];
foreach ($data[0] as $key => $value) {
$csv_header_fields[] = $key;
}
}
$csv_data = array_slice($data, 0, 2);
$credentials = $request->file('csv_file')->getClientOriginalName();
$filename = CsvData::all('csv_filename');
if(CsvData::where('csv_filename', '=' ,$credentials)->exists()){
return redirect()->back()->with('alert', 'This specific file has already been imported!');
}
else{
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
}
}
else {
return redirect()->back();
}
return view('import_fields', compact( 'csv_header_fields', 'csv_data', 'csv_data_file'));
}
public function processImport(Request $request)
{
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
if(CsvData::where('csv_data', '=' ,$csv_data)->exists()){
return redirect()->back()->with('alert', 'This file has already been imported!');
}
else{
foreach ($csv_data as $row) {
$contact = new Contact();
foreach (config('app.db_fields') as $index => $field) {
if ($data->csv_header) {
$contact->$field = $row[$request->fields[$field]];
} else {
$contact->$field = $row[$request->fields[$index]];
}
}
foreach($contact as $contacts){
$contact->posted_by = $contacts->posted_by;
$contact->employer = $contacts->employer;
$contact->address = $contacts->address;
$contact->barangay = $contacts->barangay;
$contact->citymunicipality = $contacts->citymunicipality;
$contact->province = $contacts->province;
$contact->region = $contacts->region;
$contact->position = $contacts->position;
$contact->job_description = $contacts->job_description;
$contact->salary = $contacts->salary;
$contact->count = $contacts->count;
$contact->work_location = $contacts->work_location;
$contact->nature_of_work = $contacts->nature_of_work;
$contact->min_work_exp_mos = $contacts->min_work_exp_mos;
$contact->min_educ_level = $contacts->min_educ_level;
$contact->coursemajor = $contacts->coursemajor;
$contact->min_age = $contacts->min_age;
$contact->max_age = $contacts->max_age;
$contact->min_height = $contacts->min_height;
$contact->sex = $contacts->sex;
$contact->civil_status = $contacts->civil_status;
$contact->other_qualifications = $contacts->other_qualifications;
$contact->remarks = $contacts->remarks;
$contact->accept_disability = $contacts->accept_disability;
$contact->date_posted = $contacts->date_posted['date'];
$contact->valid_until = $contacts->valid_until['date'];
$contact->date_created = $contacts->date_created['date'];
$contact->last_modified_by = $contacts->last_modified_by['date'];
$contact->date_last_modified = $contacts->date_last_modified['date'];
}
$contact->save();
return view('import_success');
}
}
}
}```
The first parameter of the import() method is not the path to the file anymore in Laravel 3.1, but the class name of the Import file you have to create.
You need to follow below steps to use import method
Step1: Create Import File using below command.
php artisan make:import CsvImport
Step2: Inside CsvImport make changes like this:
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class CsvImport implements ToCollection
{
public function collection(Collection $rows)
{
return $rows; //add this line
}
}
Step3: In Controller make changes like this:
$path = $request->file('csv_file')->getRealPath();
$rows = Excel::import(new CsvImport, $path);
Reference:
https://docs.laravel-excel.com/3.1/imports/basics.html
I need only those columns after specific indexing, which I consider practically the same use case as described in the question at the top of this page. I propose the following as solution.
$fileArr = (new BulkSampleImport)->toArray($request->file);

Codeigniter3.x calling multiple stored procedure cache

This is somewhat related to [CodeIgniter active records' problems calling multiple stored procedures
but I am not experiencing a blank page; instead when I am passing my data array to view it seems that the the preceding array also being drag to the view.
model
public function data1($student) {
$year = 1;
$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql, array($course, $student, $year, $sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
public function data2($student) {
$year = 1;
$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
Controller:
$data['data1']=data1 from my model(SP);
$data['data2']=data2 from my model(SP);
View:
foreach($data2 as key => $value ) {
echo ....;
}
Here's the PROBLEM... in the view, I only wanted to output the $data2 but to my surprise $data1 is also being output.
Does anybody else have this issue?
I JUST SOLVE IT.
Model
public function data1($student){
**$this->db->initialize();**
$year = 1;$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
public function data2($student){
**$this->db->initialize();**
$year = 1;$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
controller
$data['data1']=data1 from my model(SP);
**$this->db->close();**
$data['data2']=data2 from my model(SP);

Getting Error when converting array to a variable in laravel

I have problem when converting multiple checkbox($request->courses) to a variable(checkbox1).Because I need to insert an array to Database.
public function store(Request $request) {
$customer = new prospect;
$customer->ProspectName = $request->ProspectName;
$customer->NicNumber = $request->NicNumber;
$customer->ContactNumber = $request->ContactNumber;
$customer->ContactAddress = $request->ContactAddress;
$customer->Comments = $request->Comments;
$customer->ReferredThrough = $request->ReferredThrough;
$checkbox1 = $request->courses; //courses is an array from form
$chk = "";
foreach ($checkbox1 as $chk1) {
$chk .= $chk1 . ",";
}
$customer->IntrestedCourses = $chk;
if ($customer->save()) {
echo 'saved successfully';
} else {
echo 'error';
}
}
But I'm getting error!

Laravel library to handle messages

I have just created a library class in laravel.
class Message {
public static $data = array();
public function __construct() {
// If session has flash data then set it to the data property
if (Session::has('_messages')) {
self::$data = Session::flash('_messages');
}
}
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}
I can use this class in my views calling Message::get(). In the controllers, I can set the message as Message::set('info', 'success message here.'); and it works perfectly fine.
However, I can not use this class for flash messages redirects using Message::set('info', 'success message here.', true). Any idea, whats wrong in this code?
First problem is the constructor function is not called when using the above get and set methods, with minor modification the code is now working. :)
class Message {
public static $data = array();
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// Check the session if message is available in session
if (Session::has('_messages')) {
self::$data = Session::get('_messages');
}
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}

Resources