John Davidson

php - Override name in variable

0 comments
Message:


I have a function


public function saveImage(Request $request, $requestField, $path) {
if ($request->hasFile($requestField)) {

$image_path = public_path($this->{ $requestField });

if (File::exists($image_path)) {
File::delete($image_path);
}

$file = $request->file($requestField);
$uploadname = $this->getUploadName($file);
$pathFull = public_path($path);
if (!File::exists($pathFull, 0775, true)) {
File::makeDirectory($pathFull, 0775, true);
}
Image::make($file)->save($pathFull. $requestField. '-'. $uploadname);
$this->{ $requestField } = $path. $requestField. '-'. $uploadname;

return $file;
}

return false;
}

Next I call this function


$file = $article->saveImage($request, 'image_detail', '/storage/article/' .$article->id. '/');

The question now is, I have a $requestField, which now has the value 'image_detail'


it should have this meaning everywhere, except for these lines


$pathFull. $requestField. '-'. $uploadname
$path. $requestField. '-'. $uploadname

I want the field $requestField to be converted to such a value 'image-detail', that is, to replace the underscore '_' with a dash '-', is it possible to do this at all in this function only for separate lines?



My Answer:
Yes, it is possible to override the value of $requestField for specific lines in the function. You can create a new variable within the function and use it for those specific lines. Here's an example of how you can achieve this:

php
public function saveImage(Request $request, $requestField, $path) {
$modifiedRequestField = str_replace('_', '-', $requestField);

if ($request->hasFile($requestField)) {

$image_path = public_path($this->{$requestField});

if (File::exists($image_path)) {
File::delete($image_path);
}

$file = $request->file($requestField);
$uploadname = $this->getUploadName($file);
$pathFull = public_path($path);
if (!File::exists($pathFull, 0775, true)) {
File::makeDirectory($pathFull, 0775, true);
}
Image::make($file)->save($pathFull. $modifiedRequestField. '-'. $uploadname);
$this->{$requestField} = $path. $modifiedRequestField. '-'. $uploadname;

return $file;
}

return false;
}


In this updated function, we have added a new variable $modifiedRequestField which replaces underscores with dashes in the $requestField value. We then use $modifiedRequestField in the specific lines where we want the value to be converted.

Rate this post

4 of 5 based on 4892 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us