1

I am trying to upload a file via axios api troughr Laravel. Below is the controller code but I don't understand why Laravel tell me the variable name on line 24 is undefined. It seems to me the variable is defined...

public function store(Request $request)
{
    $this->validate($request, [
        'image' => 'required'
]);

if($request->get('image'))
{
    $image = $request->get('image');
    $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
    \Image::make($request->get('image'))->save(public_path('images/').$name);
}

$image= new FileUpload();
$image->image_name = $name;
$image->save();

return response()->json(['success' => 'You have successfully uploaded an image'], 200);
}

This is the line 24: $image->image_name = $name;

3
  • Post your line 24 code plz Commented Jun 5, 2020 at 14:49
  • $image->image_name = $name; Commented Jun 5, 2020 at 14:50
  • $image->image_name = $name; is this line 24?? Commented Jun 5, 2020 at 14:50

1 Answer 1

2

you have to make your variable in higher visibility scope :

public function store(Request $request)
{
    $this->validate($request, [
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
 $name=''; // here you define your vaiable
if($request->get('image'))
{
    $image = $request->get('image');
    $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
    \Image::make($request->get('image'))->save(public_path('images/').$name);
}

$image= new FileUpload();
$image->image_name = $name;
$image->save();

return response()->json(['success' => 'You have successfully uploaded an image'], 200);
}

more about variable scope in:

https://phppot.com/php/variable-scope-in-php/

Sign up to request clarification or add additional context in comments.

1 Comment

He also need to check the file is an image on validation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.