0

This might not be best practice- however my functions will be rather comprehensive and used by additional controllers, thus I would like to separate them from the controller's public class. (what is best practice? I just want to load the functions to specific pages/controllers.)

Laravel 7

class HomeController extends Controller
{
    function add($a, $b) {
        print($a + $b);
    }

    public function show($id) {
            add(1,2) 
    }
}
Line in Linus
  • 390
  • 8
  • 25

2 Answers2

1

You shouldn't perform logic in the controller.

I recommend you to create a Calculator folder for example where you store the sum, something like this:

The controller:

declare(strict_types=1);

namespace App\Controller;

use App\Calculator;

final class HomeController extends Controller
{
                     // $id not needed, although, if you are going to use it,
                     // try to declare the type!
    public function show() {
        return (new Calculator())->add(1, 2);
    }
}

And the calculation class:

declare(strict_types=1);

namespace App\Calculator;

final class Calculator
{
    public function add(float $firstOp, float $secondOp): float
    {
        return $firstOp + $secondOp;
    }
}

PS: Do not print in the controller, you have to follow the SRP (Single Responsibility Principle)! :) You can replace the return (new Calculator())->add(1, 2); in the show() method by a dd(new Calculator())->add(1, 2)); for example.

JesusValera
  • 629
  • 6
  • 14
0

Seems like a solution for using a trait a common practice in Laravel.

namespace App\Http\Controllers;

use  App\Traits\MySpecialFunctions;

class HomeController extends Controller
{
    use MySpecialFunctions;
}
namespace App\Traits;

trait MySpecialFunctions {
    function add($a, $b) {
        print($a + $b);
    }

    public function show($id) {
            add(1,2) 
    }
}
victoryoalli
  • 1,897
  • 2
  • 12
  • 11