Home » Php » php – How to capitalize first letter in Laravel Blade

php – How to capitalize first letter in Laravel Blade

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m using laravel (5.1) blade template engine with the localization feature.

There is a language file messages.php within the /resources/lang/en/ folder:

return [
    'welcome' => 'welcome',

In my blade template the welcome message is called using the trans method:

{{ trans('messages.welcome') }}

In some cases I need to show the same message but with first letter capitalized (“Welcome”). I don’t want to use duplicate records in the translation file.

How can I approach this?

How to&Answers:

Use PHP’s native ucfirst function:

{{ ucfirst(trans('messages.welcome')) }}

Answer:

Another way to make capitalize first letter using PHP and blade.

Controller

return view('stock.uk-lse', ['name' => 'djan']);

View

<h1>{{ ucfirst($name) }}</h1>

Answer:

Add a blade directive to the app/Providers/AppServiceProvider’s boot() function:

public function boot() {

    Blade::directive('lang_u', function ($s) {
        return "<?php echo ucfirst(trans($s)); ?>";
    });

}

This way you can use the following in your blade files:

@lang_u('messages.welcome')

which outputs: Welcome

 

You’re @lang_u(‘messages.welcome’) 🙂

Answer:

I think that the best option is use CSS text-transform property

In your CSS file:

.lowercase {
    text-transform: lowercase;
}
.uppercase {
    text-transform: uppercase;
}
.capitalize {
    text-transform: capitalize;
}

Your blade (html) file:

<p class="lowercase">{{ trans('messages.welcome') }}</p> <!-- This will display welcome -->
<p class="uppercase">{{ trans('messages.welcome') }}</p> <!-- This will display WELCOME -->
<p class="capitalize">{{ trans('messages.welcome') }}</p><!-- This will display Welcome -->

Or, the best option for me, use bootstrap

<p class="text-lowercase">{{ trans('messages.welcome') }}</p><!-- This will display welcome -->
<p class="text-uppercase">{{ trans('messages.welcome') }}</p><!-- This will display WELCOME -->
<p class="text-capitalize">{{ trans('messages.welcome') }}</p><!-- This will display Welcome -->