In this tutorial we are going to learn about global functions in Laravel.
Step 1 : In the first step we need to create a Helpers.php file in app folder.
app\Helpers.php
<?php
function getSortName($name = null)
{
$a = explode(' ', $name);
if (count($a) > 0) {
$b = substr($a[0], 0, 1);
if (isset($a[1]) && trim($a[1])) {
$b .= substr($a[1], 0, 1);
}
return $b;
} else {
return substr(str_shuffle('ABCDFGHIJKLMNOPQRSTUVWXYZ'), 0, 1);
}
}
Step 2 : Add Helpers.php file path in composer.json
Add this code in composer.json file.
composer.json
"files": [
"app/Helpers.php"
]
Step 3: Run Command
In the last step, run the following command.
composer dump-autoload
Now custom hepler is created in your Laravel aap.
let's see example of the created helper function.
Example -
<h2>{{ getSortName('John Doe') }} - John Doe</h2>
<h2>{{ getSortName('Denzel Washington') }} - Denzel Washington</h2>
Output
JD - John Doe
DW - Denzel Washington