Home > database >  Undefined variable: image while update in laravel
Undefined variable: image while update in laravel

Time:10-24

public function update_room_detail(Request $request)
{
    $request->validate([
        'room_type' => 'required',
    ]);

    if($images = $request->file('room_image')) 
    {
        foreach($images as $item):
            $var = date_create();
            $time = date_format($var, 'YmdHis');
            $imageName = $time.'-'.$item->getClientOriginalName();
            $item->move(public_path().'/assets/images/room', $imageName);
            $arr[] = $imageName;
        endforeach;
        $image = implode("|", $arr);
    }
    else
    {
        unset($image);
    }

    RoomDetail::where('id',$request->room_id)->update([
        'room_type' => $request->room_type,
        'room_image' => $image,
    ]);

    Alert::success('Success', 'Rooms details updated!');
    return redirect()->route('admin.manage-room');
}

In the above code I am trying to update image in database table. When I click on submit button then it show Undefined variable: image and when I use $image='' in else part instead of unset($image) then blank image name save. So, How can I solve this issue please help me? Please help me.

Thank You

CodePudding user response:

As per the PHP documentation:

unset() destroys the specified variables.

What this means is that it doesn't empty the value of the specified variables, they are destroyed completely.

$foo = "bar";

// outputs bar
echo $foo;

unset($foo);

// results in Warning: Undefined variable $foo
echo $foo;

You've already discovered how to handle this:

when I use $image='' in else part instead of unset($image) then blank image name save

CodePudding user response:

Fix: Note : uses Storage library feel free to use any other.

public function update_room_detail(Request $request)
{
    $request->validate([
        'room_type' => 'required',
    ]);

    $imageNames = array();

    if ($request->hasFile('room_image')) {
        $images = $request->file('room_image');
        foreach ($images as $item) {
            $var = date_create();
            $time = date_format($var, 'YmdHis');
            $imageName = $time . '-' . $item->getClientOriginalName() .".".$item->extension();
            $item->storeAs('/public/room-images-path', $imageName);
            array_push($imageNames, $imageName);
        }
    }

    RoomDetail::where('id', $request->room_id)->update([
        'room_type' => $request->room_type,
        'room_image' => $imageNames,
    ]);

    Alert::success('Success', 'Rooms details updated!');
    return redirect()->route('admin.manage-room');
}
  • Related