Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vlauciani94's avatar

Laravel logical issue

Imagine I have 2 controllers, UserController and PostController, however, I want to use a function which has a general use and doesn't thematically belong to any of those classes. Something like:

public function sum($numberOne, $numberTwo) {
    return $numberOne + $numberTwo;
}

Where am I supposed to create it in order to be able to use it in both UserController and PostController? I constantly read that it's a bad practice to call a controller method from another controller but I just can't figure out what's the alternative.

I could just create the function in each controller but then I'd be repeating myself and the code won't be easily maintainable.

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@vlauciani94

Try to create a Helpers folder in these cases inside the App folder. Then namespace the helpers. ie:

A Dates helper App\Helpers\Dates.php

namespace App\Helpers;

/**
 * collection of methods for working with dates.
 */
class Date
{
    /**
     * get the difference between 2 dates
     *
     * @param  date $from start date
     * @param  date $to   end date
     * @param  string $type the type of difference to return
     * @return string or array, if type is set then a string is returned otherwise an array is returned
     */
    public static function difference($from, $to, $type = null)
    {
        $d1 = new \DateTime($from);
        $d2 = new \DateTime($to);

        $diff = $d2->diff($d1);

        if ($type == null) {
            //return array
            return $diff;
        } else {
            return $diff->$type;
        }
    }
 }

Then in any class import the namespace:

use App\Helpers\Dates;

Then call the class

Dates::difference($from, $to);

This way you can create as many helper classes as you need, If you keep reusing the same classes over and over then it makes sense to create a package for them so they can be used on multiple projects.

2 likes

Please or to participate in this conversation.