1

I've a Custom function in App\Helpers.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:\laragon\www\projectname\app\Helpers.php:6) in C:\laragon\www\projectname\app\Helpers.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.');
        }
Dilhan
  • 25
  • 6
  • 1
    It would help if you shared relevant code files (namely the function declaration(s) and call). – nitrin0 Sep 13 '21 at 12:04
  • Since first and second declarations on the same file/line, you're most likely requiring/including the file Helpers.php multiple times instead of using require_once/include_once. – aynber Sep 13 '21 at 12:09
  • Wrap your declaration in an `if (!function_exists('CheckInvalidPlan') { function CheckInvalidPlan .... }` – apokryfos Sep 13 '21 at 12:10
  • I've updated the code question. Please check. – Dilhan Sep 13 '21 at 12:11
  • how are you loading the helper file ? btw you should load it in the composer.json then dump the autoload – N69S Sep 13 '21 at 12:23

1 Answers1

4

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 \Illuminate\Support\Carbon
     */
    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 app\Helpers.php file should never be required manually. It should be autoloaded by composer, as explained in this answer (thanks N69S).

Anthony Aslangul
  • 3,589
  • 2
  • 20
  • 30
  • Thanks all. Wrapping function with if worked. – Dilhan Sep 13 '21 at 12:34
  • @Dilhan Glad it works! I see you are new to Stackoverflow, if this issue solves your problem, don't forget to validate the answer so other people with the same error can quickly find the solution. Have a nice day. – Anthony Aslangul Sep 13 '21 at 12:38