Christophvh Christophvh - 1 month ago 14
PHP Question

Can't autoload a helper file - Laravel 5.3

I have a helper file located at

app/Helpers/Navigation.php


Helper file with namespace:

<?php

namespace App\Helpers;

class Navigation
{
public static function isActiveRoute($route, $output = 'active')
{
if (Route::currentRouteName() == $route) {
return $output;
}
}
}


i wanted to autoload this file . So in my composer.json i have this:

"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/Navigation.php"
]
},


In my view i want to do this:

<li class="{{ isActiveRoute('main') }}">


But i get the error:

Call to undefined function isActiveRoute()


Not sure what i'm doing wrong. I did composer dumpautoload when i changed the composer file. I tried installing composer again, that also didn't change anything.

Answer

For a helpers file you don't want to be using a class. You would jut define the functions you want to use.

Also, it is good practice to wrap your function in a check to make sure that function doesn't already exist.

Replace the content of you Naviation.php with:

<?php

if (! function_exists('isActiveRoute')) {

    /**
     * [Description of this function]
     * 
     * @param $route
     * @param string $output
     * @return string
     */
    function isActiveRoute($route, $output = 'active')
    {
        if (Route::currentRouteName() == $route) {
            return $output;
        }
    }
}

Hope this helps!