Osama Mohammed
Osama Mohammed

Reputation: 2861

Undefined variable: response

I am trying to get collection of data from RestFul api, when $response variable return data everything is well, but if not, i am faced a problem, this is my code:

public function showAsStage($id)
    {
        try {
       $notis = Notification::with('stage')->orderBy('created_at', 'desc')
       ->where('stage_id', $id)
       ->get();
       if(!$notis->isEmpty()){
       foreach($notis as $noti){
        $json = $noti->file ? json_decode($noti->file) : '';
        $file = $json ? (string)$json[0]->download_link : '';
        $response[] = [
            'id' => $noti->id ? $noti->id : '',
            'body' => $noti->body ? $noti->body : '',
            'stage' => $noti->stage->stage ? $noti->stage->stage : '',
            'time' => $noti->created_at ? $noti->created_at : '',
            'course' =>  "عام",
            'image' => $noti->file ?'http://172.18.23.41:8000/storage/'.$file : null
        ];
    }
}
}catch(\Exception $e){
    return $this->sendError('Server Error.', $e->getMessage());
}finally{
    return $this->sendResponse($response, 'Successfully fetch noti meta data');
}
    }

when there is no data :

 "Undefined variable: response"

Upvotes: 1

Views: 2619

Answers (1)

Soheil Rahmat
Soheil Rahmat

Reputation: 521

This happend becuase You haven't assign your variable before your foreach loop ($reponse=[]) .... So, inorder to solve this problem make an empty array before your try scope and inside your loop add your data to your array with array_push()

Upvotes: 1

Related Questions