1
votes

I would like to create a helper (function) to avoid repeating code between all views in Laravel 5. The function should be using data from the database (Eloquent), so it cannot be just a simple function or a generic view composer.

Ideally it should be something like:

{!! Helper::addLinks($text) !!}

Where the Helper class uses Eloquent to validate the $value. I would like to avoid changing all Controllers. What is the best practice for this?

Update; I have the following working prototype. This function searches the text and replaces words found from the dictionary with hyperlinks:

function addLinks($text) {
    //retrieve words from database
    $words = Words::all();

    //build dictionary with values that needs replacement
    $patterns = array();
    foreach ($words as $word) {
        $patterns[$word->id] = $word->word_name;
    }

    //build dictionary with values the replacements
    $replacements = array();
    foreach ($words as $word) {
        $replacements[$word->id] = "<a href=\"worddetails.php?id=" . $word->id . "\">" . $patterns[$word->id] . "</a>";
    }

    //return text, replace words from dictionary with hyperlinks
    return str_replace($patterns, $replacements, $text);
}

I want to use this function in several text blocks and paragraphs in the views. What approach is best?

1
You should give more arguments on why you can't use a view composer or view()->share()? Or for that matter why you can use a class method, but can't use a helper function (which from what you described and from logical standpoint would serve the same purpose)? Because the argument that it uses data from the database with Eloquent, doesn't really mean you can't use any of the options you've described.Bogdan
There's really nothing wrong with implementing it as a helper function as you have it now, since it's not that complex and it serves its purpose. If you have more helper functions that fall into the same category of functionality or if this function gets more complex and needs to be split into more support methods, then you can refactor the code into a class as @SteveBauman suggested in his answer (but at this point that's not really needed).Bogdan
As an alternative (since your helper is manipulating HTML content), you could use the laravelcollective/html package to create a HTML macro that handles this.Bogdan

1 Answers

2
votes

You could create a helper class in your app/ folder? Ex.

namespace App;

use App\Models\User;

class Helper
{
    /**
     * Description...
     *
     * @param mixed $value
     *
     * @return mixed
     */
    public static function lookup($value)
    {
        return User::find($value);
    }
}

You could utilize it by calling {!! App\Helper::lookup($value) !!}

It would be useful to know exactly what you're looking to validate with eloquent using a helper so we could properly determine the most attractive practice for the use case.