Search code examples
javascriptphpajaxlaravelintervention

how to return as array in php function


im using laravel 5.4 and intervention plugin to upload images as ajax

i will upload images in php controller and it will return a response (file name).

and the returned variables from php is an array but in javascript it going to string and i cant iterate that

 public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}

Solution

  • public function upload(Request $request) {
        $answer=array();
        $array = $request->file('image');
        $count = count($array);
        $answer=array();
        for ($i=0 ; $i<$count; $i++)
        {
            $img = Image::make($request->file('image')[$i]);
            $img->widen(800);
            $img->fit(800,600);
            $rnd = rand(10,10000);
            $location = 'images/carimages/c'.$rnd.'.jpg';
            $img->save($location);
            $answer[$i] = $rnd;
        }
    //here print $answer and check 
    //you can also check $answer with function var_dump(); 
        echo json_encode($answer);
        die;
    }
    

    Decode this array like

    json_decode($json_array,true);