How to change custom blade directive value dynamically

465 Views Asked by At

I'm trying to make a blade directive for Stichoza /google-translate-php package. But when I change the language from menu it change once. When I try to change it again it will not change. It will only work when I run php artisan view:clear command.

Here is my directive in AppServiceProvider

public function boot()
{
    Blade::directive('translate',function ($text){
        $lang =app()->getLocale();
        $changedText = GoogleTranslate::trans($text, $lang, 'en');

        return "<?php echo $changedText; ?>";
    });
}
1

There are 1 best solutions below

0
lagbox On

You are generating a static string since once the blade view is compiled to PHP and cached the PHP in that file isn't going to change which is just you echoing a string (that will not change since it is a static string).

You would want the returned PHP from the directive to be getting the locale and calling GoogleTranslate::trans if you want this to actually be dynamic as the PHP in the compiled version of the blade view is what is ran every time the view is rendered, not the blade directive (there is no Blade at this point).