5

I have the following function :

function get_user_browser() {
  $u_agent = $_SERVER['HTTP_USER_AGENT'];
  $ub = 'unknown';
  if (preg_match('/Trident\/7.0; rv:11.0/', $u_agent)) {
    $ub = "ie ie-11";
  }
  elseif(preg_match('/MSIE/i', $u_agent)) {
    $ub = "ie";
  }
  elseif(preg_match('/Chrome/i', $u_agent)) {
    $ub = "chrome";
  }
  elseif(preg_match('/Firefox/i', $u_agent)) {
    $ub = "firefox";
  }
  elseif(preg_match('/Safari/i', $u_agent)) {
    $ub = "safari";
  }
  elseif(preg_match('/Opera/i', $u_agent)) {
    $ub = "opera";
  }
  return 'browser-'.$ub;
}

I have this function declare in two blades and I got this error :

FPHP Fatal error: Cannot redeclare get_user_browser() (previously declared in /home/storage/framework/views/0800146a0e35b205e9a66bb2f00ffb2f:7) in /home/storage/framework/views/0800146a0e35b205e9a66bb2f00ffb2f on line 7

How can I fix it?

Ivan
  • 34,531
  • 8
  • 55
  • 100
flower
  • 989
  • 4
  • 16
  • 34

1 Answers1

7

Here a smart simple trick

add a file called helpers.php into your app folder

copy the function you wrote inside that file

add to composer.json under "autoload" the block:

 "files": [
  "app/helpers.php"
]

then run a composer update and you'll get the function available on all of your codebase

In this file you can add any helper functions you like, and as has already been told you should always avoid to write php code inside views

Rocco Milluzzo
  • 997
  • 8
  • 16
  • absolutely yes you can use it in every script of your project, for example in veiw by doing {{ get_user_browser() }} – Rocco Milluzzo Apr 20 '17 at 13:25
  • 1
    And then you'll get a bunch of log errors like "ERROR: Cannot redeclare get_user_browser() (previously declared... ". See https://github.com/laravel/ideas/issues/709 – McAuley Jul 27 '21 at 19:37