In this post, I would like to show you creating a JSON file and appending content to it whenever somebody submits a form. For this tutorial, I am gonna use Laravel 5.6 version.
Let’s create a brand new Laravel project via Composer Create-Project command. lets issue following command from your terminal:
composer create-project --prefer-dist laravel/laravel jsonAppendDemo
It will create a directory called jsonAppendDemo
and download all the Laravel project files and its dependencies.
After completing setup process, create a view file called contact_form.blade.php
in resources/views
directory with following HTML
.
Create a controller called ContactController.php
with below command:
$ php artisan make:controller ContactController
After creating controller lets define following methods, index
is to show the contact form and store
method is to handle the submitted data.
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()]; } }
All set lets define routes to access the form and to process the submitted data in your web.php
route file.
Route::get('/', 'ContactController@index'); Route::post('/contact/store', 'ContactController@store');
Now start the php server with below command
$ php artisan serve
Once it is started, if you visiting http://localhost:8000, you should see the following page in your browser
Once you submit the form data will be stored in the project_root/storage/app/data.json
file.
Here is my data.json
file.
[{"name":null,"email":null,"message":null,"datetime_submitted":"2018-05-02 01:36:30"},{"name":"Arjun","email":"[email protected]","message":"Hey there!","datetime_submitted":"2018-05-02 01:37:10"}]