0
votes

I am trying to store a form data into an internal JSON file with this controller code

function index() {
  return view('contact_form');
}

function store(Request $request) {

    try {
        // my data storage location is project_root/storage/app/data.json file.
        $contactInfo = Storage::disk('local')->exists('data.json') ? json_decode(Storage::disk('local')->get('data.json')) : [];

        $inputData = $request->only(['name', 'email', 'message','subject']);

        $inputData['datetime_submitted'] = date('Y-m-d H:i:s');

        array_push($contactInfo,$inputData);

        Storage::disk('local')->put('data.json', json_encode($contactInfo));

        return $inputData;

    } catch(Exception $e) {

        return ['error' => true, 'message' => $e->getMessage()];

    }
}

but it still returns with this Error

array_push() expects parameter 1 to be array null given

I'm sure it's a pretty simple error but I need some help to correct it

1
Clearly, $contactInfo is null, which suggests that Storage::disk('local')->get('data.json') is returning "null". (Side note: Surely it would be best to only make that storage request once rather than twice?) We can't tell you why it's null without knowing a lot more. But this sort of thing is something best solved by debugging, rather than via an SO question. - T.J. Crowder

1 Answers

0
votes

data.json exists but is empty or contains invalid JSON.