I am returning a json array and trying to receive it in controller but it displaying no results
Here is my model:
if ((!empty($_FILES["FlMediaImage"])) &&($_FILES["FlMediaImage"]["error"] == 0)) {
$mdImgName = $_FILES["FlMediaImage"]["name"];
$ext = substr($mdImgName, strpos($mdImgName, '.') + 1);
$mdImgName = 'adsmind_media_' . md5(uniqid(time(), true)) . '.' . $ext;
move_uploaded_file($_FILES["FlMediaImage"]["tmp_name"], ROOT . "/images/temp/" . $mdImgName);
}
$jsonArry = array(
"image_id" => 0,
"image_name" => $result->$mdImgName
);
return json_encode(array('result' => $jsonArry));
My controller is:
$imageJSON = json_decode($modObj->saveMediaImage());
$imageID = $imageJSON->result->image_id;
$imageName = $imageJSON->result->image_name;
its working
$arr= json_decode( '{"result":{"image_id":0,"image_name":null}}',FALSE);
echo $arr->result->image_id;
Can you try with it
$imageJSON = json_decode($modObj->saveMediaImage());
$imageID = $imageJSON->result->image_id;
$imageName = (isset($imageJSON->result->image_name) && !empty($imageJSON->result->image_name))?$imageJSON->result->image_name:'';
Your result is null in both vars.. $imageID and $imageName...
Change some values, like
$jsonArry = array("image_id" => '0', "image_name" => 'some_name');
and you will see result.
Related
It is not possible to transfer data from one controller to another. There is such a controller for filling mp3 files via Dropzone.JS:
public function upload(Request $request)
{
if (!$request->has('file')) {
return response()->json(['message' => 'Missing file'], 422);
}
$file = $request->file('file');
$extension = !is_null($file->extension()) ? $file->extension() : 'mp3';
$fileName = !is_null($file->getClientOriginalName()) ? rtrim($file->getClientOriginalName(), '.') : 'Unknown - Unknown.mp3';
$tracksPath = 'public/tracks/';
$globalPath = storage_path('app/public/tracks/');
$globalTrackPath = $globalPath . $fileName;
$file->move(storage_path('app/public/tracks'), $fileName);
$fileHash = sha1_file($globalTrackPath);
rename($globalTrackPath, $globalPath . $fileHash . '.' . $extension);
$track = GetId3::fromDiskAndPath('storage', 'app/public/tracks/' . $fileHash . '.' . $extension);
$t = $track->extractInfo();
$title = !empty($t['tags']['id3v2']['title']['0']) ? $t['tags']['id3v2']['title']['0'] : 'Unknown';
$artist = !empty($t['tags']['id3v2']['artist']['0']) ? $t['tags']['id3v2']['artist']['0'] : 'Unknown';
$band = !empty($t['tags']['id3v2']['band']['0']) ? $t['tags']['id3v2']['band']['0'] : '';
$album = !empty($t['tags']['id3v2']['album']['0']) ? $t['tags']['id3v2']['album']['0'] : '';
$year = !empty($t['tags']['id3v2']['year']['0']) ? $t['tags']['id3v2']['year']['0'] : '';
$genre = !empty($t['tags']['id3v2']['genre']['0']) ? $t['tags']['id3v2']['genre']['0'] : '';
$url = Storage::url($tracksPath . $fileHash . '.mp3');
if(!empty($track->getArtwork(true))) {
$tmpCoverFile = $track->getArtwork(true)->getPathname();
$coverPath = 'public/tracks/covers/';
$cover64Path = 'cover.jpg';
Storage::disk('local')->put($coverPath . '/' . $fileHash . '/' . $cover64Path, File::get($tmpCoverFile));
$cover = Storage::url($coverPath . $fileHash . '/' . $cover64Path);
} else {
$cover = '/vendor/songs-crud/images/none.png';
}
DB::table('songs_tracks')->updateOrInsert(
['hash' => $fileHash],
[
'release_id' => $request->id,
'image' => $cover,
'name' => $title,
'artist' => $artist,
'band' => $band,
'album' => $album,
'year' => $year,
'genre' => $genre,
'url' => $url,
'hash' => $fileHash,
'sortable' => '',
'slug' => $fileHash
]
);
$getTrackId = DB::table('songs_tracks')
->where('hash', $fileHash)
->first();
$id = !empty($getTrackId->id) ? $getTrackId->id : 1;
return $id;
}
The function works fine, media files are uploaded to the server and records are added to the database table. I need to pass the id to another function that generates a JSON file:
public function getTrackListJson(Request $request): \Illuminate\Http\JsonResponse
{
dd($this->upload());
$tracks = DB::table('songs_tracks')->where('id', $id)->first();
return response()->json([$tracks]);
}
I'm trying to print this function via dd(), but it gives the following error:
ArgumentCountError
Too few arguments to function SequelONE\SongsCRUD\app\Http\Controllers\Admin\TrackCrudController::upload(), 0 passed in /home/site.com/packages/sequelone/songs-crud/src/app/Http/Controllers/Admin/TrackCrudController.php on line 229 and exactly 1 expected
I can't figure out how to pass an instance of $request and do I need to pass it at all? Can anyone help with this?
When you call a function that requires parameter, or uses injection like the Laravel Request, then you need to pass it in when you call the function manually. Since you're already injecting Request $request on your getTrackListJson call, you can just pass that along.
dd($this->upload($request));
That might help
public function getTrackListJson(Request $request): \Illuminate\Http\JsonResponse
{
$id = $this->upload($request);
$tracks = DB::table('songs_tracks')->where('id', $id)->first();
return response()->json([$tracks]);
}
I was working on another person's code and when I deployed the laravel app the login page works but when I input the testing credentials it spits out this error
Trying to get property 'id' of non-object
in helpers.php line 159
at HandleExceptions->handleError(8, 'Trying to get property \'id\' of non-object', '/var/www/html/first-project/app/Helpers/helpers.php', 159, array('fields' => object(Collection), 'fieldsValues' => object(Collection), 'htmlFields' => array(), 'startSeparator' => '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">', 'endSeparator' => '</div>', 'field' => object(CustomField), 'dynamicVars' => array('$RANDOM_VARIABLE$' => 'var15931958241638660037ble', '$FIELD_NAME$' => 'phone', '$DISABLED$' => '', '$REQUIRED$' => '"required" => "required",', '$MODEL_NAME_SNAKE$' => 'user', '$FIELD_VALUE$' => '\'+136 226 5660\'', '$INPUT_ARR_SELECTED$' => '+136 226 5660'), 'gf' => object(GeneratorField), 'value' => object(CustomFieldValue)))
in helpers.php line 159
The actual function referred to is the following
function generateCustomField($fields, $fieldsValues = null)
{
$htmlFields = [];
$startSeparator = '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">';
$endSeparator = '</div>';
foreach ($fields as $field) {
$dynamicVars = [
'$RANDOM_VARIABLE$' => 'var' . time() . rand() . 'ble',
'$FIELD_NAME$' => $field->name,
'$DISABLED$' => $field->disabled === true ? '"disabled" => "disabled",' : '',
'$REQUIRED$' => $field->required === true ? '"required" => "required",' : '',
'$MODEL_NAME_SNAKE$' => getOnlyClassName($field->custom_field_model),
'$FIELD_VALUE$' => 'null',
'$INPUT_ARR_SELECTED$' => '[]',
];
$gf = new GeneratorField();
if ($fieldsValues) {
foreach ($fieldsValues as $value) {
if ($field->id === $value->customField->id) {
$dynamicVars['$INPUT_ARR_SELECTED$'] = $value->value ? $value->value : '[]';
$dynamicVars['$FIELD_VALUE$'] = '\'' . addslashes($value->value) . '\'';
$gf->validations[] = $value->value;
continue;
}
}
}
// dd($gf->validations);
$gf->htmlType = $field['type'];
$gf->htmlValues = $field['values'];
$gf->dbInput = '';
if ($field['type'] === 'selects') {
$gf->htmlType = 'select';
$gf->dbInput = 'hidden,mtm';
}
$fieldTemplate = HTMLFieldGenerator::generateCustomFieldHTML($gf, config('infyom.laravel_generator.templates', 'adminlte-templates'));
if (!empty($fieldTemplate)) {
foreach ($dynamicVars as $variable => $value) {
$fieldTemplate = str_replace($variable, $value, $fieldTemplate);
}
$htmlFields[] = $fieldTemplate;
}
// dd($fieldTemplate);
}
foreach ($htmlFields as $index => $field) {
if (round(count($htmlFields) / 2) == $index + 1) {
$htmlFields[$index] = $htmlFields[$index] . "\n" . $endSeparator . "\n" . $startSeparator;
}
}
$htmlFieldsString = implode("\n\n", $htmlFields);
$htmlFieldsString = $startSeparator . "\n" . $htmlFieldsString . "\n" . $endSeparator;
// dd($htmlFieldsString);
$renderedHtml = "";
try {
$renderedHtml = render(Blade::compileString($htmlFieldsString));
// dd($renderedHtml);
} catch (FatalThrowableError $e) {
}
return $renderedHtml;
}
its usage is as follows in the controllers. It is used many times in almost all controllers for example in the UserController.php file I think this is the calling method. I am not that well versed in laravel sorry for any noob mistakes in advance.
public function profile()
{
$user = $this->userRepository->findWithoutFail(auth()->id());
unset($user->password);
$customFields = false;
$role = $this->roleRepository->pluck('name', 'name');
$rolesSelected = $user->getRoleNames()->toArray();
$customFieldsValues = $user->customFieldsValues()->with('customField')->get();
$hasCustomField = in_array($this->userRepository->model(), setting('custom_field_models', []));
if ($hasCustomField) {
$customFields = $this->customFieldRepository->findByField('custom_field_model', $this->userRepository->model());
$customFields = generateCustomField($customFields, $customFieldsValues);
}
return view('settings.users.profile', compact(['user', 'role', 'rolesSelected', 'customFields', 'customFieldsValues']));
}
You have to change this line
From
$user = $this->userRepository->findWithoutFail(auth()->id());
To
$user = $this->userRepository->findWithoutFail(auth()->user()->id());
My first guess, change this $user = $this->userRepository->findWithoutFail(auth()->id()); to $user = $this->userRepository->findWithoutFail(auth()->user()->id);
Added auth()->user()->id;
I have this php code that is supposed to backup an image /optimise the image and the reupload the image to shopify
It works but for a few images before it timesout because there are a lot of images and each image several processes.
There are more than 500 images. Any way I can process all these images without the script timesout?
Here is the code
<?php
//ini_set("display_errors", 1);
//error_reporting(E_ALL);
ini_set('memory_limit', '-1');
require_once("inc/functions.php");
require_once("lib/Tinify/Exception.php");
require_once("lib/Tinify/ResultMeta.php");
require_once("lib/Tinify/Result.php");
require_once("lib/Tinify/Source.php");
require_once("lib/Tinify/Client.php");
require_once("lib/Tinify.php");
\Tinify\setKey("xxxxxxxxx");
$requests = $_GET;
//$hmac = $_GET['hmac'];
$serializeArray = serialize($requests);
$requests = array_diff_key($requests, array('hmac' => ''));
ksort($requests);
$token = "xxxxxx";
$shop = "xxxxx"; //no 'myshopify.com' or 'https'
$storeURL = "https://" . $shop . ".myshopify.com";
$path = realpath("images");
if ( ! is_dir($path)) {
mkdir('images', 0777);
}
$i = 1;
do {
if ($i == 1) {
$date = '2040-01-01T12:00:00-00:00';
}
$array = array('limit' => '250', 'order' => 'created_at desc', 'created_at_max' => $date);
$products = shopify_call($token, $shop, '/admin/api/2020-01/products.json', $array, 'GET');
$products = json_decode($products['response'], JSON_PRETTY_PRINT);
$i++;
foreach ($products['products'] as $product) {
$date = $product['created_at'];
foreach ($product['images'] as $image) {
$image_id = $image['id'];
$image_tag = $image['alt'];
$image_position = $image['position'];
/* Process 1: download and save image (Backup) */
$path = realpath('images/' . $product['id']);
if ( ! is_dir($path)) {
mkdir('images/' . $product['id'], 0777);
}
$fileurl = $image['src'];
$fileName = basename($image['src']);
$names = explode('?v=', $fileName);
file_put_contents('images/' . $product['id'] . '/' . $names[0], file_get_contents($image['src']));
/* End Process 1 */
/* Process 2: Optimise and save optimised Image */
$source = \Tinify\fromUrl($fileurl);
$path = realpath('images/' . $product['id'] .'/optimized');
if ( ! is_dir($path)) {
mkdir('images/' . $product['id'] .'/optimized', 0777);
}
$source->toFile("images/" . $product['id'] . "/optimized/". $names[0]);
/* End Process 2 */
$image = array(
"image" => array(
"id" => $image_id,
)
);
/* Process 3: Delete image from shopify */
$delete_image = shopify_call($token, $shop, "/admin/products/" . $product['id'] . "/images/".$image_id .".json", $image, 'DELETE');
$deleted = $delete_image['response'];
/* End Process 3 */
/* Process 4: Upload Optimised image to shopify */
$imgurl = "http://xxxx/vendor/images/" . $product['id'] . "/optimized/". $names[0];
$upload_image = array(
"image" => array(
"position"=>$image_position,
"alt"=> $image_tag,
"src"=> $imgurl
)
);
$upimage = shopify_call($token, $shop, "/admin/products/" . $product['id']. "/images.json", $upload_image, 'POST');
$uploaded = $upimage['response'];
/* End Process 4 */
}
}
} while (count($products['products']) == 250);
Any advice is highly appreciated. Thanks
OK in plain PHP I use the following to pass data to a GET
file_get_contents('https://ws.mysite.com/some.svc/here?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
I now want to apply this same piece of code to my CI project.
This Is how I have tried.
private function getResults()
{
$score = $this->actions->getSentEmailCount();
$percentilescore = $percentile = $this->actions->getPercentile($score);
$testID = '134';
$percentile = $this->actions->getPercentile($score);
$time = $this->input->get('time');
$timemath = 60000;
$timeinmseconds = $time * $timemath;
$adddata = array(
'uniID' => '5',
'testName' => 'some',
'testID' => $testID,
'total' => '10',
'correct' => $score = $this->actions->getScore(),
'percent' => $score = $this->actions->getScore(),
'dateTaken' => date('Y-m-d H:i:s'),
'timeSpent' => $timeinmseconds,
'userID' => $session_id,
);
$this->actions->add_record($adddata);
return $this->load->view('client/results', $data);
file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
}
It is not posting the data any idea why and how I should do it in CI ?
return should be the last statement in the function because it's immediately ends execution of the current function. Just put file_get_contents before return:
file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
$this->actions->add_record($adddata);
return $this->load->view('client/results', $data);
I'm creating a form to upload a file, using yii and php 5.5.3. Here is my code in the controller:
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if (!empty($setting->image_file)) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
mkdir("uploads", 0777, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
image_file is an extra attribute in model:
array('image_file', 'file', 'types' => 'gif, jpg, jpeg, png', 'maxSize' => 1024 * 1024, 'tooLarge' => 'File upload must not exceed 1MB.'),
and here is the view:
<input type="file" name="settings[store_logo]" class="input-small">
$setting->image_file->saveAs can successfully upload the file, but it also generates
Error 500 Creating default object from empty value
What went wrong? Any help would be much appreciated.
i guess, the $_FILES['settings']['name'] has a empty value in the last Key.
If you upload a File(s), they will be process as expected. The last value in your POST-array cause a NULL-return here:
// $setting === null
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName))
and this call throws the 500.
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
This is my Version of your code:
<?php
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
// catch null-return
if(!$setting) {
echo "can't find stuff at<pre>"; print_r($settingName); echo "</pre>";
continue;
}
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if ($setting->image_file) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
// dont 0777!
mkdir("uploads", 0740, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
?>