-1

I'm trying to add some function into Laravel like encrypting or decrypting a value, formatting paragraph etc

Currently I have added my function into controller class like this

public static function encrypt_decrypt($action, $string) {
    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = 'secret';
    $secret_iv = 'secret_2';

    // hash
    $key = hash('sha256', $secret_key);

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    if ($action == 'encrypt') {
        $outputs = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($outputs);
    } else if ($action == 'decrypt') {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}

Now currently I'm calling my function like

{{ App\Http\Controllers\Items::encrypt_decrypt("encrypt", 'user_name') }}

The above method works Perfectly but doesn't seem nice and correct to me, because writing the whole path makes it difficult.

Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64
Aniket Singh
  • 857
  • 4
  • 16
  • 39
  • 1
    You should put this logic into a separate class and you could [create a global helper](https://stackoverflow.com/questions/37339475/how-to-create-helper-methods-on-laravel-not-a-facade/37339565#37339565) and use it like `{{ encrypt_decrypt(...) }}`. Also, why don't you want to use `encrypt()` and `decrypt()` Laravel helpers? – Alexey Mezenin Jul 20 '17 at 17:35
  • Hello i tried this answer in my project now it gives an error Class not found https://stackoverflow.com/a/37339615/6027966 – Aniket Singh Jul 20 '17 at 17:47
  • Try my answer maybe? – Alexey Mezenin Jul 20 '17 at 17:51

2 Answers2

2

Import the class, then:

namespace Foo\Bar;

use App\Http\Controllers\Items;

$encrypted = Items::encrypt_decrypt(
    'encrypt', 
    'user_name'
);

For reference, see:

localheinz
  • 9,179
  • 2
  • 33
  • 44
0

first of all you should pul the logic in a separate class , second of all its better you define you'r function as PUBLIC rather than public static.

then where ever you need it ( like you'r controller ) you just call with $this ... of course you have to build our constructor in controller. it will be something like this :

public function __construct(YOURMODEL $someVariable)
{
return $this->$someVariable = $someVariable;
}

$this->$someVariable->YourFunction ;
Alireza Amrollahi
  • 930
  • 3
  • 12
  • 27