burtonLowel
burtonLowel

Reputation: 794

Laravel: How to return JSON response when using foreach

I am uploading images using Vue and my Laravel backend endpoint looks like this below. I am unsure of what to put in the response though since it is a foreach that iterates through each file and uploads them but I still want to return the response as JSON.

public function upload(Request $request)
{
    $files = $request->file('images');

    foreach ($files as $file) {
        Storage::put('store/assets/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
    }

    return response()->json(????);
}

Upvotes: 0

Views: 1044

Answers (1)

Nima Ka
Nima Ka

Reputation: 163

public function upload(Request $request)
{
    $files = $request->file('images');
    $stack = [];
    foreach ($files as $file) {
        $fileName = Storage::put('store/assets/', file_get_contents($file->getRealPath()),
            ['visibility' => 'public']);
        array_push($stack, $fileName);
    }

    return response()->json($stack);
}

Or you can just do like that:

$data = ["success" => 1];

return response()->json($data);

My offer: if your query is executed succesfully $data=[ "stat"=>1, "data"=>[ "first"=>1, ... ] ] else $data=[ "stat"=>0, "error"=>"Not successfull" ]

Upvotes: 2

Related Questions