Helper or Common function in Laravel 9

Helper or Common function in Laravel 9

01-Oct-2022
| |
Image Carousel

Some functions in laravel are like you have to use in every controller , like saving an image ,some cURL request , some converting converting functions (Bytes to MB,GB) or some functions when we are using apis to return json format .
Liike we have some other methods of using resuable code like Traits , functions in models but when you have to use these methods you first have to initialise like if we have traits , so to use them ( we have to intialize and call the method use   and same in model we have to initialize in the controller ) but what if we want use that code in Blade  file ......

So here we use a helper or common function which is used in every single file  in larvel. Make a folder structure like this app/Common/helper.php 

so here we make manually a fiile name helper.php inside Common folder now we define it in autoload files inside composer.json  in root directory don't replace   the whole code

just add the helper directory in autoload funtion   Copy

  "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
        "files": ["app/Common/helper.php"]
    }

and hit composer dump-autoload  Copy

composer dump-autoload 

add the  following code in helper.php  Copy 

<?php
 
use App\Models\User;
 
function prx($arr)
{
    echo "<pre>";
    print_r($arr);
    die();
}
 
function convert($size, $unit)
{
    if ($unit == "KB") {
        return $fileSize = round($size / 1024, 4) . 'KB';
    }
    if ($unit == "MB") {
        return $fileSize = round($size / 1024 / 1024, 4) . 'MB';
    }
    if ($unit == "GB") {
        return $fileSize = round($size / 1024 / 1024 / 1024, 4) . 'GB';
    }
}

call the function in any controller Copy 

  public function showDatainMB()
    {
        $value  =   1048576;
        $value  =   convert($value,'MB');
        prx($value);
    }

 

Tags: helper or common function using laravel 9, helper using laravel , common function in laravel 9, how to make reusable code in laravel 9 , how to call common function in laravel 9,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
Related Articles
Load More

Newsletter