DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

Easier icons in your Laravel Blade templates

At AddWorking we're huge fans of Font Awesome. It's so easy to use and have so many icon, it's really awesome.

In today's snippet I'm going to show you how you can create a custom Blade directive to use icons like that:

<a href="...">
    @icon('bacon') Click to recieve bacon!
</a>
Enter fullscreen mode Exit fullscreen mode

Yes, bacon is an existing icon.

Bear with me, you may learn a thing or two on how Laravel handles assets & templates.

Component

First, install Font-Awesome:

composer require components/font-awesome
Enter fullscreen mode Exit fullscreen mode

I personnaly prefer using composer for this but you can use NPM also.

Stylesheet

First add this to webpack.mix.js:

mix.styles([
    'vendor/components/font-awesome/css/fontawesome.css',
], 'public/css/all.css');
Enter fullscreen mode Exit fullscreen mode

see Laravel doc for details about mix.

Run npm run production (or dev...)

Then, add this to your template's <head> section:

<link rel="stylesheet" href="{{ asset('css/all.css') }}">
Enter fullscreen mode Exit fullscreen mode

Service Provider

Now we need a new blade directive: @icon.

Update app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Blade::directive('icon', function ($expression) {
            return "<i class=\"fas fa-fw fa-{{ $expression }}\"></i>";
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

don't forget to clear your view cache with php artisan view:clear each time you update a Blade directive!

Done.

That was it. Now you can @icon('check') anywhere in your views.


Don't hesitate to leave a comment if you're having trouble with this snippet.

Top comments (2)

Collapse
 
charlescaballero profile image
charlesCaballero

I'm having trouble.. I followed your instructions but its just show a box and not the icon I want.

Collapse
 
mrteeceehun profile image
mrteeceehun

Just ran into the same thing.
The issue is that the referenced webfonts in Font-Awesome CSS cannot be found, so you'll need to copy those with Laravel Mix like:

mix.copy('vendor/components/font-awesome/webfonts', 'public/webfonts');