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?
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. – Bogdanlaravelcollective/html
package to create a HTML macro that handles this. – Bogdan