1

I have a Trait called TricksTrait with a few string parsing and replacing functions that I use alot (most I read from the net and remove unwanted chars for domPdf || Maatwebsite Excel Html rendering engines) in my laravel Controllers.
I pass reference to the Trait by using use TricksTrait within my class FilmController. The methods are used by referencing $this e.g. $this->str_replace_json('The Fox & Hound').

The thing is I want to use the TricksTrait method str_replace_json within a view that is outputting html in a loop. Using $this->str_replace_json($variable) in my view fails with error Call to undefined method Illuminate\View\Engines\CompilerEngine::str_replace_json() .

So I tried creating a function variable by passing the TricksTrait method to a variable within a controller class function:

class FilmController extends Controller
{
    use TricksTrait;
    public function downloadFile ($id) {
        $str_replace_json = "self::str_replace_json"; // gives error Class 'self' not found
    }
}

The Trait function reference fails as Not found for all the below:

"self::str_replace_json"; // gives error Class 'self' not found
"FilmController::str_replace_json"; // gives error Class 'FilmController' not found
"TricksTrait::str_replace_json"; // gives error Class 'TricksTrait' not found

How do I pass a Trait method reference to a variable that has function scope within the Class that inherits the Trait?

Hmerman6006
  • 1,622
  • 1
  • 20
  • 45
  • `str_replace_json` qualifies to be just a helper method now. You make new helper files that has these utility functions and autoload them. – nice_dev May 03 '21 at 15:45
  • https://stackoverflow.com/questions/28290332/best-practices-for-custom-helpers-in-laravel-5 looks like what you need. I don't really see the point of a trait if it's a "generic" helper. – Jeto May 03 '21 at 15:48
  • I see what both you mean. Certain functions within my TricksTrait it seems is a bit over the top. Thanks Jeto and nice_dev. Or ServiceProvider. – Hmerman6006 May 03 '21 at 15:55

0 Answers0