Encrypting Large Files in Laravel easy

Encrypting Large Files in Laravel easy

Encrypting Large Files in Laravel easy. but very important

How To Encrypt Large Files in Laravel, encrypting files is easy and very important

Recently, I came across what I thought would be a pretty common problem. In a Laravel project where users can upload files of any size, the files needed to be encrypted at rest for security purposes.

Laravel provides encryption facilities, but they are designed mostly for encrypting values. Encrypting a small file like an image with the encrypt helper method works fine, but in the process, the file contents need to be loaded in memory, which for large files becomes an issue.

In this tutorial, I will describe all the steps needed to encrypt large files into a brand new Laravel project.

First, create a new Laravel project using the Laravel installer. We’ll call it security-app:

laravel new security-app

At the time of writing this tutorial, we are using Laravel v6.5.2.

Because we have used the Laravel installer, we already have an application key generated and added to our .env file. If you are using other installation methods, don’t forget to generate a new app key using:

 php artisan key:generate

Because we are using Laravel Valet, we should already have the security-app.testdomain created for us. If you are using another development environment, you should add a local domain to point to the new project.

Since the front-end scaffolding has been moved to Laravel UI since v6, we will install the laravel/ui package.

composer require laravel/ui — dev

Next, we will install the bootstrap and auth scaffolding:

php artisan ui bootstrap --auth

And compile everything.

npm install && npm run dev

We also need to configure our database access credentials in the .env file and run the initial migrations:

php artisan migrate

We can now create a new user and log in to see the user dashboard.

Note: For the purpose of this demonstration, we will create a basic upload form, but in your application, you should consider using a more sophisticated upload functionality, using chunked uploads for large files.

Laravel auth scaffolding has created for us a /home route, a HomeController,and a home.blade.php view file.

Let’s edit the home.blade.php file and add a form and an upload field:

<form action="{{ route('uploadFile') }}" method="post" enctype="multipart/form-data" class="my-4">

    <div class="form-group">
        <div class="custom-file">
            <input type="file" class="custom-file-input" id="userFile" name="userFile">
            <label class="custom-file-label" for="userFile">Choose a file</label>

    <button type="submit" class="btn btn-primary">Upload</button>

    @if (session()->has('message'))
        <div class="alert alert-success mt-3">
            {{ session('message') }}

Next, we will add a new route:

Route::post(‘/home’, ‘[email protected]’)->name(‘uploadFile’);

And a new store method to the HomeController. This method will store the uploaded file in a subdirectory with the current user ID, within a files directory (storage/app/files/{user-id}).

Note: This is poor practice and should not be used in a production app. We are relying on the filesystem to get a user’s files for demonstration purposes to keep this tutorial small, but a more robust system using database tables for keeping track of each user’s files is required in a production app.

     * Store a user uploaded file
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
    public function store(Request $request)
        if ($request->hasFile('userFile') && $request->file('userFile')->isValid()) {
            Storage::putFile('files/' . auth()->user()->id, $request->file('userFile'));
        return redirect()->route('home')->with('message', 'Upload complete');

This is the stage where we need to encrypt the user uploaded files. We will pull in the file-vault package:

composer require soarecostin/file-vault

The package allows access to the FileVault facade, which exposes a few methods for encrypting and decrypting a file, as well as a few methods to set options like a different encryption key for each file, or specifying the Laravel filesystem disk that the file belongs to.

We will use the FileVault::encrypt($file) method to encrypt our user-uploaded file. This function will delete the original unencrypted file, and replace it with a file with the same name and an additional .encextension.

If you would like to name your file differently, you can pass in the desired name as the second parameter to the encrypt method. If you’d like to preserve your original file, you can use the encryptCopy method.

This is what our storemethod looks like now:

     * Store a user uploaded file
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
    public function store(Request $request)
        if ($request->hasFile('userFile') && $request->file('userFile')->isValid()) {
            $filename = Storage::putFile('files/' . auth()->user()->id, $request->file('userFile'));
            // Check to see if we have a valid file uploaded
            if ($filename) {
        return redirect()->route('home')->with('message', 'Upload complete');

Next, we need to see all of the user-uploaded files and we also need a way of downloading them.

We will create a new downloadFile route and a new downloadFile method in HomeController:

Route::get(‘/files/{filename}’, ‘[email protected]’)->name(‘downloadFile’);
     * Download a file
     * @param  string  $filename
     * @return \Illuminate\Http\Response
    public function downloadFile($filename)
        // Basic validation to check if the file exists and is in the user directory
        if (!Storage::has('files/' . auth()->user()->id . '/' . $filename)) {
        return response()->streamDownload(function () use ($filename) {
            FileVault::streamDecrypt('files/' . auth()->user()->id . '/' . $filename);
        }, Str::replaceLast('.enc', '', $filename));

The downloadFilemethod uses the Laravel native streamDownload response, which accepts a callback.

Inside the callback, we are calling the streamDecrypt method of the FileVault facade provided by the package_,_ which will decrypt the file and serve it segment-by-segment to the streamDownload method, allowing your users to download the decrypted file directly.

We now need to display all the user’s files below the upload form. For this, we will send a $files variable from the index method of HomeController to the home.blade.php view file and display the user’s files in the home.blade.php file, below the upload form.

     * Show the application dashboard.
     * @return \Illuminate\Contracts\Support\Renderable
    public function index()
        $files = Storage::files('files/' . auth()->user()->id);
        return view('home', compact('files'));
<ul class="list-group">
    @forelse ($files as $file)
        <li class="list-group-item">
            <a href="{{ route('downloadFile', basename($file)) }}">
                {{ basename($file) }}
        <li class="list-group-item">You have no files</li>

You can find the entire Laravel app created in this tutorial in this GitHub repo.

Thank you for reading !

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

In Laravel 6 tutorial, we learn how to use PHP artisan command interface (CLI) to clear the cache from Laravel 6.8 application. How To Clear Cache in Laravel 6.8 Application using Artisan Command Line Interface (CLI)? How to clear route cache using php artisan command? How to easily clear cache in Laravel application? How to clear config cache in PHP Laravel via artisan command? How to clear Laravel view cache? How to Reoptimized class in Laravel via artisan CLI?

Today in this tutorial, we are going to learn how to clear route cache, laravel application cache, config cache, view cache and reoptimized class in a Laravel 6.8 application using artisan command-line interface.

I’m pretty sure many of you may have found yourself gotten into the situation where you do not see changes in the view after making the changes in the app.

Laravel application serves the cached data so caching problem occurs due to the robust cache mechanism of Laravel.

But, if you are still facing this issue, then you do not have to worry further. Let me do the honour of introducing you some of the best artisan commands to remove the cache from your Laravel app via PHP artisan command line interface.

Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application.

Table of Contents

  • Clear Route Cache in Laravel
  • Clear Laravel Application Cache
  • Clear Config Cache via PHP Artisan
  • Clear Laravel View Cache
  • Reoptimized Class
Clear Route Cache in Laravel

Laravel caching system also takes routes in consideration, to remove route cache in Laravel use the given below command:

php artisan route:cache
Clear Application Cache in Laravel

Run the following command to clear application cache:

php artisan cache:clear
Clear Config Cache in Laravel

Run the following command to clear config cache:

php artisan config:cache
Clear View Cache in Laravel

Run the following command to clean your view cache:

php artisan view:clear
Reoptimize Class

Run the below command to reoptimize the class loader:

php artisan optimize


We have completed this Laravel 6 tutorial, In this tutorial we learned how to use php artisan command to clear the cache from your Laravel application. We have answered the following questions in this article.

  • How to clear route cache using php artisan command?
  • How to easily clear cache in Laravel application?
  • How to clear config cache in PHP Laravel via artisan command?
  • How to clear Laravel view cache?
  • How to Reoptimized class in Laravel via artisan CLI?

Now, it’s your time to let me know what do you think about this laravel 6 article. Go forth and try these super awesome artisan commands and let me know how these commands are helping you.

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather. Laravel Weather is a good package which we can use to get weather data. It's a wrapper around Open Weather Map API (Current weather). A wrapper around Open Weather Map API (Current weather)

🌤️ A wrapper around Open Weather Map API (Current weather)


You can install the package via composer:

composer require gnahotelsolutions/laravel-weather
$weather = new Weather();

// Checking weather by city name
$currentWeatherInGirona = $weather->get('girona,es');

// You can use the city id, this will get you unambiguous results
$currentWeatherInGirona = $weather->find('3121456');


By default the package uses metric for Celsius temperature results, this can be modified using the configuration file or on the fly:

$weather = new Weather();

$currentWeatherInGirona = $weather->inUnits('imperial')->get('girona,es');


By default the package uses es for the description translation, this can be modified using the configuration file or on the fly:

$weather = new Weather();

$currentWeatherInGirona = $weather->inLanguage('en')->get('girona');

Guzzle Client Instance

If you need to use another instance of Guzzle, to modify headers for example:

$weather = new Weather();

$guzzle = $this->getSpecialGuzzleClient();

$currentWeatherInGirona = $weather->using($guzzle)->get('girona');


composer test

Tips for you to Writing PHP clean code and Secure

Tips for you to Writing PHP clean code and Secure

Any code when written in a clean, easy to understand, for any programmer who works on it later, it is essential that the codes are structured, clean, secured and easily maintainable.

Any code when written in a clean, easy to understand and formatted way is readily accepted and acclaimed by one and all. It is essential that the codes we write should be able to be understood by all, because the same programmers need not necessarily work on the same set of codes always. For easy identification and understanding of the codes for any programmer who works on it later, it is essential that the codes are structured, clean, secured and easily maintainable.

Explained below are few of the best practices that are followed to maintain clean and easy to understand PHP codes. They are not in any order of importance, so all are the practices mentioned are essential and carry equal importance:

1. Commenting on every important action that is performed is very essential.

This not only helps in easy identification of the need of that particular code, but also gives a neat look to the codes as well.

// Function for login checking

2. Avoid unwanted usage of conditional statements:

This not only increases the execution time but also makes the coding long and complex.
For example,

If (condition1==true){
code which satisfies the above condition
} else {
perform   die(); or exit();

The same set of codes can be written as:


// display warning message.
die("Invalid statement");

This reduces the execution time and also makes the codes easily maintainable.

The same can also be written as

$response_text = ( $action == "edit" ) ?  "the action equals edit" : "the action does not equal edit";
echo $response_text;

Here ternary operators have been used, instead of using conditional statements, to simplify the coding further.

3. Code indentation, in order to highlight statement beginnings and endings.

If(mysql_num_rows($res)>0) {
echo $a->first_name;
}//ending of while loop
}//ending of if condition

4.Avoid unwanted html tags in the PHP code:

In the example given below, the PHP compiler goes through each and every line of the code and executes the function, which is time consuming.

For example:

echo "<table>";
echo “<tr>”;
echo “<td>”;
echo “Hai welcome to php”;
echo “</td>”;
echo </tr>”;
echo “</table>”;

Instead of the above we can simply say,

<td><?php echo "Hai welcome to php"; ?></td>

Here the PHP compiler would execute the particular server code only, here in the example, , instead of creating html tags, as the html codes are alien to PHP. This facilitates in cutting down unnecessary checking time of the PHP compiler, thereby saving code execution time.

5. Clear Code with in assigning values to Mysql Arguments:

For example

$sql="select first_name,last_name,email_address from tbl_user where user_id=".$user_id." and member_type='".$member_type."'";


In the above example, you can see that the PHP values are included in the query condition. Also there are lots of concatenations done to the variables within the query.


$sql="select first_name,last_name,email_address from tbl_user where user_id="%d" and member_type='"%s"'";


By using this query, the values are automatically assigned to the appropriate positions, thereby saving the execution time and as well as the programmers can easily find the related values to the arguments passed.

6. Using Arrays:

It is always better to use arrays in PHP, as they are quite easy to manage and easily understandable as well.


Using Split array is also a very good way of coding in PHP. However, there are ways to use a split array:
Rather than:

echo $products[$iC].”<br>”;

Instead, the codes can be written as follows:

foreach($products as $product_value){
echo $product_value;

foreach is specifically for arrays. When it is used, they reduce the coding length and also the functioning time.

7. Consistent naming:

It is always advisable to name classes, objects and others consistently. This helps in easy identification for other programmers who might work later on the project. Also names of files in local directories should also be easy to understand.

8. Using Objects [class]

Though they seem to be quite complicated to the newcomers, Objects are very useful as it reduces code repetition and also facilitates easier changes to the codes. In that when a class is used, it makes it more flexible to work with.

A simple class functionality is explained below:


Class shopping_cart{

var $cart_items;

function add_product_item($cart_number,$quantity){


// Call the class function
$cart=new shopping_cart();


9. Appropriate use of Looping codes:

There are many looping codes available in PHP. It is very important to choose the right looping code for the right purpose, so that execution time can be saved upon and the work also would get over sooner.

For example, instead of:

$res=mysql_query("select * from tbl_products");
for($iC=0;$iC< mysql_num_rows($res);$iC++){
echo mysql_result($res,$iC);

The same can be coded this way, in order to reduce the execution time:

$res=mysql_query("select * from tbl_products");
echo $obj->column_name1;

10. Using of case switches:

It is definitely advantageous to use Case switches instead of If conditions. This is because switch statements are equivalent to using a series of IF statements on the same expression.

Example of using a series of If statements:

echo "result1";
echo "result2";
echo "result3";
echo "result 4";

The same thing can be expressed in a simpler way using the switch case, which greatly reduces the operational time:

case Value1:
echo "result1";

case Value2:
echo "result2";

case Value3:
echo "result3";

echo "result4";


11. Using single codes instead of double quotes:

Though these two serve various purposes, using single quotes help in faster execution of the loops than when using double quotes.

For example, a simple example of printing 1500 lines of information, can be done in two ways as:

//Using double quotes
print “SerialNo : $serialno. WorkDone : $workdone. Location: $location”;

The same can be written with single quotes:

//Using single quotes
print ‘SerialNo :’.$serialno.’. WorkDone : ‘.$workdone’. Location‘.$location’.';

Here, the second line of codes works much faster than the first one, where the strings have to be analyzed completely, all the 1500 times. In the second line of codes, no actual string analyzing takes place. Just combination of the strings happens in order to make the printing possible.

Few of these tips might sound quite familiar, but they have been included here in order to refresh the best practices that can be followed to get clean, secured at the same time easy to maintain PHP codes.

Thank you for reading ! Please share if you liked it!