Thursday, September 5, 2019

Append text to a file in Laravel

In Laravel some time you want to add error logging or some other text information related to your code running status in a file. I'm going to show how you can achieve that

First you need to use the inbuilt File class inside your controller, for that include the below line on the controller above your class definition (Refer the below picture)
use File;

Once you include the above line now you can call the function from the File class, the function we need for appending the text to a file is append() function.

This function will append any text you are providing to the end of the already created file, or if the file is not available it will create a file in the name you provide and append the text to it.

Next thing is we need to pass two parameters to this function, first parameter is storage location with file name and the second one is the text you want to append (Refer the belo picture)

In the above picture I'm using a function in the place of storage location and file name, which is storage_path() this function will get the storage directory in the root path of your laravel application. and if the file is available on that location it will append the text to the particular file or else it will create a file inside the storage directory and append the text to it

In the above picture once this function run first time it will create a file called error.log inside logs directoy which is there inside the storage directory and append the text "Error 1" to it without the quotes.
* The append function will not create the folder if it is not available already, so it will pass an error. In the above case, If there is no logs directory you need to create logs directory inside storage directory to successfully test the code