In our last article I showed you to create file and this article will cover to Prepend or Append File Content in Laravel application. To perform the file system based operations like create, replace, prepend or append File Content file in laravel, we use File
class or Storage
class in laravel. Laravel provides inbuilt library to access the file system and we can do multiple robust operations using the libraries. In this tutorial i will show you to make a file with content in laravel.
Sometimes we want to append or prepend raw information in text or json file so for this purpose we need to the file in our application. File can be open in different modes like append, read only or read and write.
In this article I will use Illuminate\Filesystem\Filesystem
class and facade File::prepend()
and FIle::append()
method to create and replace a new file .
Method accepts two parameters as belowput
1. File::
: To append the content in the file at last.prepend
()
File::prepend($path, $contents, $lock)
File::prepend(public("logs/user.text"),"Simple content");
Example Usage:
2. File::
: To append the content at the beginning of the existing file.
()append
File::append($path, $contents)
Example Usage:
File::append(public("logs/user.text"),"Simple content");
Here I called append
or prepend with 2 parameters first parameter tells to the name of file and second parameter to add the contents to the file
Let’s understand it with example step by step
Step 1: Create a fresh laravel project
Open a terminal window and type below command to create a new project
composer create-project --prefer-dist laravel/laravel blog
You can also read this to start with new project
Step 2 : Create controller
Let’s create a controller and add method checkAndAppendFile
php artisan make:controller FileController
and add the below code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
class FileController extends Controller
{
public function checkAndAppendFile(Request $request){
$storageDestinationPath=public_path("users.log");
File::append($storageDestinationPath,"This is simple content appended");
return response("File changed successfully");
}
}
Step 3: Create two routes in routes/web.php
Create a route to create the directory
routes/web.php
<?php
use App\Http\Controllers\checkAndCreateFile;
use Illuminate\Support\Facades\Route;
Route::get("/append-file",[FileController::class,"checkAndAppendFile"]);