Laravel - Maatwebsite/Laravel-Excel without input file - laravel

I have implemented Maatwebsite/Laravel-Excel with input file, this works fine.
public function import(Request $request)
{
$path = $request->file('file');
if (!is_file($path))
{
dd("file excel missing");
}
Excel::import(new ProductsSerialsImport,request()->file('file'));
return redirect()->back()->with('success', 'File updated!');
}
Route::post('products_serials/import', 'ProductsSerialsController#import')->name('products_serials.import');
I done something of this, but don't understand where I can receive excel file without pass through input file.
public function import(Request $request)
{
$path = "storage/excel/file.xlsx";
if(!File::exists($path)) {
dd("missing excel file!");
}
Excel::import(new ProductsSerialsImport, $path);
return redirect()->back()->with('success', 'File updated!');
}
How I can update excel file from route => 'products_serials/import' skipping upload file through the input file?
Thanks in advance!

There's a constructor. from docs it will be like this
ProductsSerialImport.php
class ProductsSerialImport implements ToCollection {
private $file;
public function __construct($file)
{
$this->file = $file;
}
public function collection(Collection $row)
{
foreach($row as $r) {
Model::create(['name', $this->file]); // Just for example
}
}
}
YourController.php
Excel::import(new ProductsSerialsImport(request()->file('file')));

Related

Call to a member function getRealPath() on string while sending an email

Call to a member function getRealPath() on string error occurs while sending an email.
Controller
public function store(CareerRequest $request)
{
$requestData = $request->all();
$filenameWithExt = $request->file('resume')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('resume')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$request->file('resume')->storeAs('candidateResume', $fileNameToStore);
$requestData["resume"] =$fileNameToStore ;
Career::create($requestData);
return redirect()->back();
}
Mailable
class CareerMail extends Mailable
{
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->subject('Career - '. $this->data->subject)
->view('emails.career')
->attach($this->data['resume']->getRealPath(),
[
'as' => $this->data['resume']->getClientOriginalName(),
'mime' => $this->data['resume']->getClientMimeType(),
]);
}
}
Error on line
->attach($this->data['resume']->getRealPath(),
You are trying to use function getRealPath() on your $fileNameToStore, which is a string : $filename.'_'.time().'.'.$extension.
getRealPath() will only work on $request()->file('resume')->getRealPath().
If you want to get the information of your file, you should use Uploaded file instance instead or get the file instance you stored.

Fetch image as a url from mysql database in laravel Api

I want to fetch the image from database as a URL like http://127.0.0.1:8000/uploads/category/image.png
but the result I am getting is the name of the file not the URL.
This is the model class:
class CategoryModel extends Model
{
protected $table="tb_category";
public $timestamps = false;
protected $fillable = [
'id',
'name',
'image'
];
}
This is my controller class:
class CategoryController extends Controller
{
//
public function viewPage(){
return view('category');
}
public function saveCategory(Request $request){
$category = new CategoryModel();
$category->name=$request->input('name');
if($request->hasfile('image')){
$file=$request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time().'.'.$extension;
//$headers = array('Content-Type' => 'application/octet-stream');
$file->move('uploads/category/',$filename);
$category->image =$filename;
$category->_image =$filename;
}
else{
return $request;
$category->image='';
$category->_image=null;
}
$category->save();
return view('category')->with('category',$category);
}
public function getCategories(){
$res = CategoryModel::get(
['id','name','image'
]
);
return response()->json($res,200);
}
}
In your saveCategory method, you're storing $filename in 'image' column.
Change it to store path.
public function saveCategory(Request $request){
$category = new CategoryModel();
$category->name=$request->input('name');
if($request->hasfile('image')){
$file=$request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time().'.'.$extension;
$file->move('uploads/category/',$filename);
$category->image ='http://127.0.0.1:8000/uploads/category/'.$filename; //This is where you need to save absolute path of the image.
}
else{
return $request;
}
$category->save();
return view('category')->with('category',$category);
}
One more problem here is that you've written code after return $request; in else statement. Any code written after return is unreachable for the interpreter and will not be executed.

Laravel encryp($value) not saved to database

I have the following code in my user model, and $value is encrypted on set, but not saved to the database (MariaDB 10.2 VARCHAR(255) utf8mb4_unicode_ci). When I display the encrypted value and paste it manually to the database, it is decrypted properly. Am I missing something?
public function getMyKeyAttribute($value)
{
if ( $value )
{
return Crypt::decrypt($value);
}
else
{
return $value;
}
}
public function setMyKeyAttribute($value)
{
if ( $value )
{
return Crypt::encrypt($value);
}
else
{
return $value;
}
}
Controller:
public function update($id, UsersRequest $request)
{
$user = \Auth::user();
$user->update($request->all());
return redirect('users');
}
Request (nothing related to myKey):
class UsersRequest extends FormRequest
{
public function authorize() {
return true;
}
public function rules()
{
return [
'name' => 'required'
];
}
public function messages()
{
return [ ];
}
}
Setting an attribute requires you to fill the attributes property. The method itself should return a void.
public function setMyKeyAttribute($value)
{
if ($value)
$this->attributes['my_key'] = Crypt::encrypt($value);
}
See https://laravel.com/docs/5.5/eloquent-mutators#defining-a-mutator for more details.
If you're using PHP 7.1, you can use this (will encrypt empty strings but you should check that before setting the attribute):
public function setMyKeyAttribute(string $value) : void
{
$this->attributes['my_key'] = Crypt::encrypt($value);
}

write_file not working in code igniter

iam trying to file writing using following code is not done
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('file');
}
public function index()
{
$data = "Some file data";
if (!write_file(base_url()."test.txt", $data))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
}
After i changed the code its done
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('file');
}
public function index()
{
$data = "Some file data";
if (!write_file('M:\xampp\htdocs\tt\text.txt', $data))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
}
Any one can explain what is the problem in above code
When creating a file with write_file make sure your folder/directory is there where you would like to create file
Then I would recommend using FCPATH
$data = "Some file data";
if (write_file(FCPATH . '/document/text.txt', $data) == FALSE)
{
echo 'Unable to write the file';
} else {
echo 'File written!';
}
My directory
application
document
system
index.php

What is best practice for adding additional controller to Magento Core Modules

I want to add additional controller named SkuController to CatalogSearch Core module.
What is best practice to do this?
Thanks.
all extra funcionality should made by module. I recomend made a new module with the new controller.
Whatever you do, do not modify the core, but create a custom module, and ensure you always call the parent functions where possible.
Use ModuleCreater to simplify this task:
http://www.magentocommerce.com/magento-connect/modulecreator.html
Have a look at Ivan's video tutorial, just ignore the php unit testing bit, but he explains the whole lot, especially half way during the video.
http://vimeo.com/35937480
Also look at this sample for some more ideas:
http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-3-magento-controller-dispatch
Good best practice ideas shared on both links.
A controller class could look like this:
class Mycompany_myMod_Adminhtml_myModController extends Mage_Adminhtml_Controller_action
{
protected function _initAction() {
$this->loadLayout()
->_setActiveMenu('custompromos/items')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
return $this;
}
public function indexAction() {
$this->_initAction()
->renderLayout();
}
public function editAction() {
$id = $this->getRequest()->getParam('id');
//Some code here
}
public function newAction() {
$this->_forward('edit');
}
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
//Some code here
}
}
public function deleteAction() {
if( $this->getRequest()->getParam('id') > 0 ) {
try {
//Some code here
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
public function massDeleteAction() {
//Some code here
$this->_redirect('*/*/index');
}
public function massStatusAction()
{
//Some code here
$this->_redirect('*/*/index');
}
public function exportCsvAction()
{
$fileName = 'somedata.csv';
$content = $this->getLayout()->createBlock('mymodule/adminhtml_mymodule_grid')
->getCsv();
$this->_sendUploadResponse($fileName, $content);
}
public function exportXmlAction()
{
$fileName = 'somedata.xml';
$content = $this->getLayout()->createBlock('mymodule/adminhtml_mymodule_grid')
->getXml();
$this->_sendUploadResponse($fileName, $content);
}
protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
{
$response = $this->getResponse();
$response->setHeader('HTTP/1.1 200 OK','');
$response->setHeader('Pragma', 'public', true);
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
$response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
$response->setHeader('Last-Modified', date('r'));
$response->setHeader('Accept-Ranges', 'bytes');
$response->setHeader('Content-Length', strlen($content));
$response->setHeader('Content-type', $contentType);
$response->setBody($content);
$response->sendResponse();
die;
}
}

Resources