Laravel 5 Helpers

As I developed an application with Laravel 5 I encountered situations where I wanted to allow people to reference things, kind of like how @paddoswam becomes a link and a notification.

So my first attempt became something like this with the text being “today I used preg_replace @paddoswam with some help from @someone”.

[php]{!! preg_replace("/\@([A-Za-z]+[A-Za-z0-9]+)/", ‘<a href="$1">@$1</a>’, $comment->text) !!}[/php]

It works but it’s not very pretty and only 1 functions.

Next up I tried to create a comment field where you could add bold and italic text the result, I shall not share, wasn’t pretty..

So I moved it to a class in App/Helpers/Text.php:


namespace \App\Helpers;

class Text
public static function twitterize($text)
// e() is Laravel’s default escape function just like {{ $variable }} would work
$text = e($text);

// the same as in our blade template
$text = preg_replace("/\@([A-Za-z]+[A-Za-z0-9]+)/", ‘<a href="$1">@$1</a>’, $text);

return $text;

And registered a class alias:


[php]’aliases’ => [
// …
‘TextHelper’ => App\Helpers\Text::class,

Now we have readable and relatively pretty Blade template code like this:

[php]{!! TextHelper::twitterize($comment->text) !!}
{!! TextHelper::formatted($article->text) !!}[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *