not able to upload xlsx or docx file in laravel 5.7 - excel-2010

Hi I'm trying to upload a xlsx file to the laravel api, (I am able to upload (images, xls) files), but I'm not able to do so I am getting the below details as follows
request my header has Content-Type as multipart/form-data
response for the $file = request()->file('user_bulk_upload'); var_dump($file);
object(Illuminate\Http\UploadedFile)[424]
private 'test' (Symfony\Component\HttpFoundation\File\UploadedFile) => boolean false
private 'originalName' (Symfony\Component\HttpFoundation\File\UploadedFile) => string 'sudo1.xlsx' (length=10)
private 'mimeType' (Symfony\Component\HttpFoundation\File\UploadedFile) => string 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' (length=65)
private 'error' (Symfony\Component\HttpFoundation\File\UploadedFile) => int 0
protected 'hashName' => string 'jFWNUFGJVuAMNi8p9BdzuZmKXu2MA5RtiOpopBPO' (length=40)
private 'pathName' (SplFileInfo) => string 'C:\xampp\tmp\php2472.tmp' (length=24)
private 'fileName' (SplFileInfo) => string 'php2472.tmp' (length=11)
and for $path = $file->store('excel', 'public');var_dump($path);
I'm getting response as
'excel/jFWNUFGJVuAMNi8p9BdzuZmKXu2MA5RtiOpopBPO.bin' (length=50)
Can anyone help me with this.

I solve this problem with this function bellow used for multiple uploads:
public static function uploadFiles(int $ticketId, array $files)
{
$dir = self::documentsDir($ticketId);
/** #var Illuminate\Http\UploadedFile $file */
foreach ($files as $file) {
$fileName = \Carbon\Carbon::now()->format('Ymd')."-".strtotime(\Carbon\Carbon::now()).".".$file->getClientOriginalExtension();
$file->storeAs($dir, $fileName, ['disk' => 'public']);
}
}

Related

Yii2-curl oAuth2 with zoho

I am working on Yii2. I have a URL which on hitting a browser is redirected to my redirect URI.
URL
https://accounts.zoho.com/oauth/v2/auth?scope=ZohoBugTracker.projects.ALL,ZohoBugTracker.bugs.ALL&client_id=1000&response_type=code&access_type=offline&redirect_uri=http://11.111.111.111:7000/api/oauth/zoho_auth
When I hit the above URL it will redirect to my redirect URI while giving a code
Redirect URI
After hitting the above URL the redirect URI is http://11.111.111.111:7000/api/oauth/zoho_auth?code=1000&location=us&accounts-server=https%3A%2F%2Faccounts.zoho.com
Redirect URI Response
{"Message":"No HTTP resource was found that matches the request URI 'http://11.111.111.111:7000/api/oauth/zoho_auth?code=1000&location=us&accounts-server=https:%2F%2Faccounts.zoho.com'."}
How to get the code from the above response?
Update 1
As per suggestion given. I tried to send a GET request using linslin. Below is my code
public static function authToken()
{
$curl = new curl\Curl();
$response = $curl->setGetParams([
'scope' => 'ZohoBugTracker.projects.ALL,ZohoBugTracker.bugs.ALL',
'client_id' => '1000',
'response_type' => 'code',
'access_type' => 'offline',
'redirect_uri' => 'http://11.111.111.111:7000/api/oauth/zoho_auth',
])
->get('https://accounts.zoho.com/oauth/v2/auth');
echo $response;
exit();
}
And then called this function inside a function through which I am actually creating bugs using zoho API
Testing my API via POSTMAN
http://localhost:225/inventory-web/api/web/v1/installation/email?ref_no=28373340485858U&customer_id=37030315933&site_snap_name=28373340485858U_1530958224_site_9.jpg&flag=1
My email function is written inside a API controller. So, it will first hit the issueSetup($param1,$param2)
public function actionEmail()
{
.
.
.
.
Installations::setupEmail($param1, $param2, $param3);
.
.
.
}
The above function setupEmail($param1,$param2,$param3) is inside my controller.
public static function setupEmail($ref_no, $customer_id, $install_id)
{
.
.
.
.
.
list(params.....)= Installations::issueSetup($param1,$param2);
.
.
.
.
}
issuSetup funciton
public static function issueSetup($param1,$param2)
{
.
.
.
.
$token = Installations::authToken();
exit();
.
.
.
.
}
After hitting the API the I am getting no response in POSTMAN just the empty window
Any help would be highly appreciated.
Its working quite fine when you enable SSL and check the response code / response header to redirect to the userAuth form on Zuhu:
$curl = new \linslin\yii2\curl\Curl();
/** #var Curl $response */
$curl->setGetParams([
'scope' => 'ZohoBugTracker.projects.ALL,ZohoBugTracker.bugs.ALL',
'client_id' => '1000',
'response_type' => 'code',
'access_type' => 'offline',
'redirect_uri' => 'http://11.111.111.111:7000/api/oauth/zoho_auth',
])->setOption(CURLOPT_SSL_VERIFYPEER, true)
->setOption(CURLOPT_SSL_VERIFYHOST, false)
->setOption(CURLOPT_CAINFO, 'C:/Ampps/apache/conf/ssl_crt/cacert.pem')
->get('https://accounts.zoho.com/oauth/v2/auth');
$responseHeaders = $curl->responseHeaders;
if ($curl->responseCode === 302 && isset($responseHeaders['Location'])) {
header("location: ".$responseHeaders['Location']);
die();
}
Have you tried this to get Error
if ($curl->errorCode === null) {
echo $response;
} else {
echo '<pre>';print_r($curl->errorCode);
}

Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for translate

I have written a controller plugin to get the MVC translator using ZF 2.5.
Here is my translate controller plugin
namespace Freedom\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\I18n\Translator\Translator;
/**
* Translate
*
*/
class Translate extends AbstractPlugin
{
/**
*
* #var Translator
*/
private $translator;
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
/**
* Translate message
* #param string $message
* #param string $textDomain
* #param string $locale
* #return string
*/
public function __invoke($message, $textDomain = 'default', $locale = null)
{
return $this->translator->translate($message, $textDomain, $locale);
}
/**
*
* #return Translator
*/
function getTranslator()
{
return $this->translator;
}
}
and is factory
namespace Freedom\Controller\Plugin\Service;
use Zend\ServiceManager\FactoryInterface;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Freedom\Controller\Plugin\Translate;
/**
* TranslateFactory
*
*/
class TranslateFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new Translate($container->get('translator'));
}
public function createService(ServiceLocatorInterface $container)
{
return $this($container->getServiceLocator(), Translate::class);
}
}
and finally in my module.config
'controller_plugins' => [
'factories' => [
'checkRedirect' => 'Freedom\Controller\Plugin\Service\CheckRedirectFactory',
'translate' => 'Freedom\Controller\Plugin\Service\TranslateFactory',
],
],
The problem I have is that I am getting this error and I can't understand why.
Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for translate
As you can see I have registered the plugin in my module.config but the plugin manager can't find it. I have checked that the controller_plugins key exists in the config and that my namespacing is correct. I also have another plugin called checkRedirect that produces the same error.
I simply can't figure out what is going on, please can someone tell me what I have missed, many thanks.
I finally found the problem, I was calling the plugin from the controllers constructor which does not work. Calling from an action, everything ok.
please try this, may be it help you.
I think all is ok, but you need to update this,
'controller_plugins' => [
'factories' => [
'checkRedirectPlugin' => 'Freedom\Controller\Plugin\Service\CheckRedirectFactory',
'translatePlugin' => 'Freedom\Controller\Plugin\Service\TranslateFactory',
],
'aliases' =>[
'checkRedirect' => 'checkRedirectPlugin',
'translate' => 'translatePlugin'
]
],
now use aliases, you can now access from your controller as,
$this->translate()

Get data from a join of two tables yii2

I'm new to yii2 and trying to make a dropdown in yii2, but i can't get the data in a correct way from the tables. This are persona and docente and they are related through id_persona. The fields i need are docente.id_docente and persona.nombre and i get them by making a join:
$personas = Persona::find()->with('docentes')->all();
then i map the data i need for the dropdown:
$data = ArrayHelper::map($personas, 'docente.id_docente','nombre');
I get the error the following error:
Getting unknown property: app\models\Persona::docente
what am i doing wrong?
When i do a var_dump($personas) i get:
array (size=4)
0 =>
object(app\models\Persona)[71]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=15)
'id_persona' => int 15
'nombre' => string 'prueba' (length=6)
'apellido' => string 'prueba' (length=6)
...
1 =>
object(app\models\Persona)[90]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=15)
'id_persona' => int 16
'nombre' => string 'sebastian' (length=9)
'apellido' => string 'carreras' (length=8)
...
The fields from table docente are not in there, i don't understand...
Model persona:
/**
* #return \yii\db\ActiveQuery
*/
public function getAlumnos()
{
return $this->hasMany(Alumno::className(), ['id_persona' =>'id_persona']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getDocentes()
{
return $this->hasMany(Docente::className(),['id_persona'=>'id_persona']);
}
model docente
/**
* #return \yii\db\ActiveQuery
*/
public function getIdPersona()
{
return $this->hasOne(Persona::className(), ['id_persona' => 'id_persona']);
}

GRAILS: send parameter to renderEditor.template

I need to send a parameter to the file renderEditor.template (After of installing of "grails install-templates"), but I have no idea how. Can anyone help me? Thanks.
The binding variables available to renderEditor.template are fixed in DefaultGrailsTemplateGenerator
def binding = [pluginManager: pluginManager,
property: property,
domainClass: domainClass,
cp: cp,
domainInstance:getPropertyName(domainClass)]
domainClass being the GrailsDomainClass, property being the GrailsDomainClassProperty that was passed to the renderEditor(p) call in the scaffolding template, and cp being the corresponding ConstrainedProperty. You may be able to extract what you need from one of those.
For other people who got here via Google with the same problem (as I did)
I've managed to do so in similar way as Ian Roberts suggested, but you don't need to create new implementation for Template Generator. All you need is to create a proxy implementation for org.codehaus.groovy.grails.commons.GrailsDomainClassProperty
inside of _form.gsp I did just created new property with added data:
p = new HgfGrailsDomainClassProperty(p, prefix, domainClass)
if (display) { %>
<hgf:ifAllowedOnField action="show" field="${p.name}">
<hgf:ifReasonToShow reasonElement="${p.name}" bean="\${${propertyName}}">
<div class="fieldcontain \${hasErrors(bean: ${propertyName}, field: '${prefix}${p.name}', 'error')} ${required ? 'required' : ''} ${(cp?.metaConstraints?.hiddenField)?'hiddenProperty':''}">
<label for="${prefix}${p.name}">
<g:message code="${domainClass.propertyName}.${prefix}${p.name}.label" default="${p.naturalName}" />
<% if (required) { %><span class="required-indicator">*</span><% } %>
</label>
${renderEditor(p)}
...
Implementation can look something like this:
package sk.hoppo.hgf;
import org.codehaus.groovy.grails.commons.GrailsDomainClass
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty
public class HgfGrailsDomainClassProperty implements GrailsDomainClassProperty {
private final String domainSuffix = "Instance";
private GrailsDomainClassProperty property;
String prefix;
String domainInstance;
public HgfGrailsDomainClassProperty(GrailsDomainClassProperty property, String prefix, GrailsDomainClass parentDomainClass) {
super();
this.property = property;
this.prefix = prefix;
domainInstance = getPropertyName(parentDomainClass);
}
private String getPropertyName(GrailsDomainClass domainClass) {
return "${domainClass.propertyName}${domainSuffix}";
}
#Override
public int getFetchMode() {
return property.getFetchMode();
}
#Override
public String getName() {
return property.getName();
}
...
Inside the renderEditor.template you just access the send data:
sb << '<hgf:securedField'
sb << ' name="' << property.prefix << property.name << '"'
sb << ' field="' << property.prefix << property.name << '"'
BTW. with this I've made composition (embedding) to work with my custom renderEditor correctly

Symfony cyrillic routing slug

I have problem whit slugify routing parameter. I want to replace all intervals and symbols with "-". When parameter is with latin letters all work, but if I try to slugify parameter whit cyrillic letters I get error.
routing:
catTests:
url: /cat/:id/:name_slug
class: sfDoctrineRoute
options: { model: categories, type: object }
param: { module: categories, action: testsByCat }
requirements:
id: \d+
slug functions:
static public function slugify($text)
{
// replace all non letters or digits by -
$text = preg_replace('/\W+/', '-', $text);
// trim and lowercase
$text = strtolower(trim($text, '-'));
return $text;
}
public function getNameSlug()
{
$text= Category::slugify($this->getName());
return $text;
}
Example:
i have two names in databace:
english language
Български език
Normally whitin function url is :
english+language
Български+език
When i put function result is :
english-language
and on cyrillic version parameter is empty.
Empty module and/or action after parsing the URL "/cat/1/" (/).
I recommend you to use Doctrine::urlize instead of your own slugify function (since your are using Doctrine).
And then, replace your function like:
public function getNameSlug()
{
return Doctrine_Inflector::urlize($this->getName());
}
edit:
In fact, it seems that Doctrine doesn't well handle Cyrillic (even in the 2.0). You will have to handle it on your own. I found this function:
public static function replaceCyrillic ($text)
{
$chars = array(
'ґ'=>'g','ё'=>'e','є'=>'e','ї'=>'i','і'=>'i',
'а'=>'a', 'б'=>'b', 'в'=>'v',
'г'=>'g', 'д'=>'d', 'е'=>'e', 'ё'=>'e',
'ж'=>'zh', 'з'=>'z', 'и'=>'i', 'й'=>'i',
'к'=>'k', 'л'=>'l', 'м'=>'m', 'н'=>'n',
'о'=>'o', 'п'=>'p', 'р'=>'r', 'с'=>'s',
'т'=>'t', 'у'=>'u', 'ф'=>'f', 'х'=>'h',
'ц'=>'c', 'ч'=>'ch', 'ш'=>'sh', 'щ'=>'sch',
'ы'=>'y', 'э'=>'e', 'ю'=>'u', 'я'=>'ya', 'é'=>'e', '&'=>'and',
'ь'=>'', 'ъ' => '',
);
return strtr($text, $chars);
}
And then :
public function getNameSlug()
{
$slug = Category::replaceCyrillic($this->getName());
return Doctrine_Inflector::urlize($slug);
}
You can fix that behaviour globaly all around your project too.
Thanks to symfony autoloader which prepends your global directories before the plugin's you can do it this way:
mkdir lib/doctrine
touch lib/doctrine/Inflector_Cyrilic.php
touch lib/doctrine/Sluggable.php
touch test/unit/TransliterationTest.php
lib/doctrine/Inflector_Cyrilic.php:
<?php
class Doctrine_Inflector_Cyrilic extends Doctrine_Inflector
{
/**
* #param string $text
* #param Doctrine_Record $record
*
* #return string
*/
public static function urlizeExtended($text, $record) {
// we need to use other method name because of PHP strict standards (one more attribute unlike parent so its not compatible)
// $record attribute is given here standardly, it was only not used before
//XXX this sollution expect youll have all slugs in Translation records (in I18n in schema.yml)
// You can alter this conditions how do you need for your project
// this is important because this should not be used on other writing systems
if (preg_match('/Translation$/', get_class($record))) {
if ($record->lang === 'ru') {
$text = self::cyrilicToLatin($text);
}
}
return parent::urlize($text);
}
/**
* #param string $text
*
* #return string
*/
public static function cyrilicToLatin ($text)
{
$chars = array(
'ґ'=>'g','ё'=>'e','є'=>'e','ї'=>'i','і'=>'i',
'а'=>'a', 'б'=>'b', 'в'=>'v',
'г'=>'g', 'д'=>'d', 'е'=>'e', 'ё'=>'e',
'ж'=>'zh', 'з'=>'z', 'и'=>'i', 'й'=>'i',
'к'=>'k', 'л'=>'l', 'м'=>'m', 'н'=>'n',
'о'=>'o', 'п'=>'p', 'р'=>'r', 'с'=>'s',
'т'=>'t', 'у'=>'u', 'ф'=>'f', 'х'=>'h',
'ц'=>'c', 'ч'=>'ch', 'ш'=>'sh', 'щ'=>'sch',
'ы'=>'y', 'э'=>'e', 'ю'=>'u', 'я'=>'ya', 'é'=>'e',
'ь'=>'', 'ъ' => '',
);
return strtr($text, $chars);
}
}
lib/doctrine/Sluggable.php:
<?php
/**
* we cannot use inheritance here because we are replacing class by otherone with the same name
*/
class Doctrine_Template_Sluggable extends Doctrine_Template
{
/**
* Array of Sluggable options
*
* #var string
*/
protected $_options = array(
'name' => 'slug',
'alias' => NULL,
'type' => 'string',
'length' => 255,
'unique' => TRUE,
'options' => array(),
'fields' => array(),
'uniqueBy' => array(),
'uniqueIndex' => TRUE,
'canUpdate' => FALSE,
'builder' => array('Doctrine_Inflector_Cyrilic', 'urlizeExtended'),
'provider' => NULL,
'indexName' => NULL
);
/**
* Set table definition for Sluggable behavior
*
* #return void
*/
public function setTableDefinition()
{
$name = $this->_options['name'];
if ($this->_options['alias']) {
$name .= ' as ' . $this->_options['alias'];
}
if ($this->_options['indexName'] === NULL) {
$this->_options['indexName'] = $this->getTable()->getTableName().'_sluggable';
}
$this->hasColumn($name, $this->_options['type'], $this->_options['length'], $this->_options['options']);
if ($this->_options['unique'] == TRUE && $this->_options['uniqueIndex'] == TRUE) {
$indexFields = array($this->_options['name']);
$indexFields = array_merge($indexFields, $this->_options['uniqueBy']);
$this->index($this->_options['indexName'], array('fields' => $indexFields,
'type' => 'unique'));
}
$this->addListener(new Doctrine_Template_Listener_Sluggable($this->_options));
}
}
test/unit/TransliterationTest.php:
<?php
// some bootstrapping of your tests
$record = Doctrine_Core::getTable('YourTable')->create(array(
'record params....'
));
$record->Translation['ru']->name = 'холодильник';
$record->save();
$t->ok(preg_match('/^holodilnik/', $record->Translation['ru']->slug), ' RU slug transliterated cyrilic to latin');
Take care if You want to use it in cli tasks, you'll have to preload it manualy there, because of its running environment. sf1.4 cli tasks has its own specific running env and in my projects it does not preloads this classes before Doctrine original ones..
//i have this in my abstract class which is parent of each my cli tasks
require_once(implode(DIRECTORY_SEPARATOR, array(
__DIR__, '..',
'Doctrine',
'Sluggable.php'
)));

Resources