shahr's avatar
Level 10

Undefined variable: image_name

I want to upload and display image, but i get error Undefined variable: image_name

    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $image_name = $image->getClientOriginalName();
        $image->move(public_path('images/images'), $image_name);
    }
    Style::create([
        'style_name' => $request->style_name,
        'image' => $image_name,
        'email' => $request->email,
        'style_logo' => $filename,
        'founder' => $request->founder,
        'website' => $request->website,
    ]);
0 likes
4 replies
click's avatar

that is because you are doing:

if (/* something *) {
   $image_name = 'something else';
}

if it doesn't pass your if statement the image_name is never defined (as the error already told you).

There is no file being uploaded in your sample. And I think you want to move the Style::create() inside the if statement. If no file is being uploaded it shouldn't create a new style I suppose?

click's avatar

If you pay me my hourly rate, yes I could do that.

But you should be able to figure this out. Read the error again: "Undefined variable: image_name". What does this mean? The variable $image_name is not defined. So you have to figure out why is this happening and when? Looking at your code it can happen if there is no file uploaded (see the if statement).

walidabou's avatar

That means the image is not uploaded so php won't execute your if block. make sure that you upload the image correctly, or as temporary solution you can define the variable before the if statement like this:

$image_name = 'default.jpg';

  if ($request->hasFile('image')) {
        $image = $request->file('image');
        $image_name = $image->getClientOriginalName();
        $image->move(public_path('images/images'), $image_name);
    }
    Style::create([
        'style_name' => $request->style_name,
        'image' => $image_name,
        'email' => $request->email,
        'style_logo' => $filename,
        'founder' => $request->founder,
        'website' => $request->website,
    ]);

So in this case if the image was uploaded correctly the $image_name will be the one inside if block, otherways it will be 'default.jpg'

Please or to participate in this conversation.