Laravel 8 Custom Helper function PHP Fatal error: Cannot redeclare functionName() previously declared in C:(patth)Helpers.php

I’ve a Custom function in AppHelpers.php. When I use the function in if statement in a blade file. I see error in Laragon error logs.

PHP Fatal error:  Cannot redeclare CheckInvalidPlan() (previously declared in C:laragonwwwprojectnameappHelpers.php:6) in C:laragonwwwprojectnameappHelpers.php on line 6

However things works as expected. But why is this error causing and how can I fix it?

#Update

This is my function in Helpers.php

function CheckInvalidPlan($id)

{

    if (Plan::find($id) == null)
    {
        return true;
    }

}

This is my if statement in Controller.
if (CheckInvalidPlan ($request->plan_id))
        {
            return back()->with('invalid', 'Invalid membership plan spesified.');
        }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can bypass this error by checking if your function already exists:

if(! function_exists('CheckInvalidPlan')) {
    function CheckInvalidPlan($id)
    {
        if (Plan::find($id) == null)
        {
            return true;
        }
    }
}

That’s how Laravel helpers are declared:

if (! function_exists('today')) {
    /**
     * Create a new Carbon instance for the current date.
     *
     * @param  DateTimeZone|string|null  $tz
     * @return IlluminateSupportCarbon
     */
    function today($tz = null)
    {
        return Date::today($tz);
    }
}

However, a cleaner approach would be to understand why your helpers file is loaded twice.

It is hard to tell you exacly where the error could be, however you should inspect all your classes, the appHelpers.php file should never be required manually. It should be autoloaded by composer, as explained in this answer (thanks N69S).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x