I would like to create helper functions to avoid repeating code between views in Laravel 5:
view.blade.php
Foo Formated text: {{ fo
Having sifted through a variety of answers on SO and Google, I still couldn't find an optimal approach. Most answers suggest we leave the application and rely on 3rd party tool Composer to do the job, but I'm not convinced coupling to a tool just to include a file is wise.
Andrew Brown's answer came the closest to how I think it should be approached, but (at least in 5.1), the service provider step is unnecessary. Heisian's answer highlights the use of PSR-4
which brings us one step closer. Here's my final implementation for helpers in views:
First, create a helper file anywhere in your apps directory, with a namespace:
namespace App\Helpers;
class BobFinder
{
static function bob()
{
return '<strong>Bob?! Is that you?!</strong>';
}
}
Next, alias your class in config\app.php
, in the aliases
array:
'aliases' => [
// Other aliases
'BobFinder' => App\Helpers\BobFinder::class
]
And that should be all you need to do. PSR-4
and the alias should expose the helper to your views, so in your view, if you type:
{!! BobFinder::bob() !!}
It should output:
<strong>Bob?! Is that you?!</strong>
**
** create new helper
<?php
namespace App\Helpers;
use Illuminate\Database\Eloquent\Collection;
class StatusHelper
{
protected static $_status = [
1=> [
'value' => 1,
'displayName' => 'Active',
],
2 => [
'value' => 2,
'displayName' => 'Inactive',
],
3 => [
'value' => 3,
'displayName' => 'Delete',
],
];
public static function getStatusesList()
{
$status = (new Collection(self::$_status))->pluck('displayName', 'value')->toArray();
return $status;
}
}
Use for the controller and any view file
use App\Helpers\StatusHelper;
class ExampleController extends Controller
{
public function index()
{
$statusList = StatusHelper::getStatusesList();
return view('example.index', compact('statusList'));
}
}
This is my HelpersProvider.php file:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider
{
protected $helpers = [
// Add your helpers in here
];
/**
* Bootstrap the application services.
*/
public function boot()
{
//
}
/**
* Register the application services.
*/
public function register()
{
foreach ($this->helpers as $helper) {
$helper_path = app_path().'/Helpers/'.$helper.'.php';
if (\File::isFile($helper_path)) {
require_once $helper_path;
}
}
}
}
You should create a folder called Helpers
under the app
folder, then create file called whatever.php
inside and add the string whatever
inside the $helpers array.
Done!
I'm no longer using this option, I'm currently using composer to load static files like helpers.
You can add the helpers directly at:
...
"autoload": {
"files": [
"app/helpers/my_helper.php",
...
]
},
...
For Custom Helper Libraries in my Laravel project, I have created a folder with name Libraries
in my Laravel/App
Directory and within Libraries directory, I have created various files for different helper libraries.
After creating my helper files I simply include all those files in my composer.json file like this
...
"autoload": {
"classmap": [
"database"
],
"files": [
"app/Libraries/commonFunctions.php"
],
"psr-4": {
"App\\": "app/"
}
},
...
and execute
composer dump-autoload
Here's a bash shell script I created to make Laravel 5 facades very quickly.
Run this in your Laravel 5 installation directory.
make_facade.sh -f <facade_name> -n '<namespace_prefix>'
Example:
make_facade.sh -f helper -n 'App\MyApp'
If you run that example, it will create the directories Facades
and Providers
under 'your_laravel_installation_dir/app/MyApp'.
./app/MyApp/Facades/Helper.php
./app/MyApp/Facades/HelperFacade.php
./app/MyApp/Providers/HelperServiceProvider.php
After it is done, it will display a message similar to the following:
===========================
Finished
===========================
Add these lines to config/app.php:
----------------------------------
Providers: App\MyApp\Providers\HelperServiceProvider,
Alias: 'Helper' => 'App\MyApp\Facades\HelperFacade',
So update the Providers and Alias list in 'config/app.php'
Run composer -o dumpautoload
The "./app/MyApp/Facades/Helper.php" will originally look like this:
<?php
namespace App\MyApp\Facades;
class Helper
{
//
}
Now just add your methods in "./app/MyApp/Facades/Helper.php".
Here is what "./app/MyApp/Facades/Helper.php" looks like after I added a Helper function.
<?php
namespace App\MyApp\Facades;
use Request;
class Helper
{
public function isActive($pattern = null, $include_class = false)
{
return ((Request::is($pattern)) ? (($include_class) ? 'class="active"' : 'active' ) : '');
}
}
This is how it would be called:
===============================
{!! Helper::isActive('help', true) !!}
This function expects a pattern and can accept an optional second boolean argument.
If the current URL matches the pattern passed to it, it will output 'active' (or 'class="active"' if you add 'true' as a second argument to the function call).
I use it to highlight the menu that is active.
#!/bin/bash
display_syntax(){
echo ""
echo " The Syntax is like this:"
echo " ========================"
echo " "$(basename $0)" -f <facade_name> -n '<namespace_prefix>'"
echo ""
echo " Example:"
echo " ========"
echo " "$(basename $0) -f test -n "'App\MyAppDirectory'"
echo ""
}
if [ $# -ne 4 ]
then
echo ""
display_syntax
exit
else
# Use > 0 to consume one or more arguments per pass in the loop (e.g.
# some arguments don't have a corresponding value to go with it such
# as in the --default example).
while [[ $# > 0 ]]
do
key="$1"
case $key in
-n|--namespace_prefix)
namespace_prefix_in="$2"
echo ""
shift # past argument
;;
-f|--facade)
facade_name_in="$2"
shift # past argument
;;
*)
# unknown option
;;
esac
shift # past argument or value
done
fi
echo Facade Name = ${facade_name_in}
echo Namespace Prefix = $(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
echo ""
}
function display_start_banner(){
echo '**********************************************************'
echo '* STARTING LARAVEL MAKE FACADE SCRIPT'
echo '**********************************************************'
}
# Init the Vars that I can in the beginning
function init_and_export_vars(){
echo
echo "INIT and EXPORT VARS"
echo "===================="
# Substitution Tokens:
#
# Tokens:
# {namespace_prefix}
# {namespace_prefix_lowerfirstchar}
# {facade_name_upcase}
# {facade_name_lowercase}
#
namespace_prefix=$(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
namespace_prefix_lowerfirstchar=$(echo ${namespace_prefix_in} | sed -e 's#\\#/#g' -e 's/^\(.\)/\l\1/g')
facade_name_upcase=$(echo ${facade_name_in} | sed -e 's/\b\(.\)/\u\1/')
facade_name_lowercase=$(echo ${facade_name_in} | awk '{print tolower($0)}')
# Filename: {facade_name_upcase}.php - SOURCE TEMPLATE
source_template='<?php
namespace {namespace_prefix}\Facades;
class {facade_name_upcase}
{
//
}
'
# Filename: {facade_name_upcase}ServiceProvider.php - SERVICE PROVIDER TEMPLATE
serviceProvider_template='<?php
namespace {namespace_prefix}\Providers;
use Illuminate\Support\ServiceProvider;
use App;
class {facade_name_upcase}ServiceProvider extends ServiceProvider {
public function boot()
{
//
}
public function register()
{
App::bind("{facade_name_lowercase}", function()
{
return new \{namespace_prefix}\Facades\{facade_name_upcase};
});
}
}
'
# {facade_name_upcase}Facade.php - FACADE TEMPLATE
facade_template='<?php
namespace {namespace_prefix}\Facades;
use Illuminate\Support\Facades\Facade;
class {facade_name_upcase}Facade extends Facade {
protected static function getFacadeAccessor() { return "{facade_name_lowercase}"; }
}
'
}
function checkDirectoryExists(){
if [ ! -d ${namespace_prefix_lowerfirstchar} ]
then
echo ""
echo "Can't find the namespace: "${namespace_prefix_in}
echo ""
echo "*** NOTE:"
echo " Make sure the namspace directory exists and"
echo " you use quotes around the namespace_prefix."
echo ""
display_syntax
exit
fi
}
function makeDirectories(){
echo "Make Directories"
echo "================"
mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
mkdir -p ${namespace_prefix_lowerfirstchar}/Providers
mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
}
function createSourceTemplate(){
source_template=$(echo "${source_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
echo "Create Source Template:"
echo "======================="
echo "${source_template}"
echo ""
echo "${source_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}.php
}
function createServiceProviderTemplate(){
serviceProvider_template=$(echo "${serviceProvider_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
echo "Create ServiceProvider Template:"
echo "================================"
echo "${serviceProvider_template}"
echo ""
echo "${serviceProvider_template}" > ./${namespace_prefix_lowerfirstchar}/Providers/${facade_name_upcase}ServiceProvider.php
}
function createFacadeTemplate(){
facade_template=$(echo "${facade_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
echo "Create Facade Template:"
echo "======================="
echo "${facade_template}"
echo ""
echo "${facade_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}Facade.php
}
function serviceProviderPrompt(){
echo "Providers: ${namespace_prefix_in}\Providers\\${facade_name_upcase}ServiceProvider,"
}
function aliasPrompt(){
echo "Alias: '"${facade_name_upcase}"' => '"${namespace_prefix_in}"\Facades\\${facade_name_upcase}Facade',"
}
#
# END FUNCTION DECLARATIONS
#
###########################
## START RUNNING SCRIPT ##
###########################
display_start_banner
init_and_export_vars
makeDirectories
checkDirectoryExists
echo ""
createSourceTemplate
createServiceProviderTemplate
createFacadeTemplate
echo ""
echo "==========================="
echo " Finished TEST"
echo "==========================="
echo ""
echo "Add these lines to config/app.php:"
echo "----------------------------------"
serviceProviderPrompt
aliasPrompt
echo ""
There are some great answers here but i think this is the simplest. In Laravel 5.4 (and prob earlier versions too) you can create a class somewhere convenient for you, eg App/Libraries/Helper.php
class Helper() {
public function uppercasePara($str) {
return '<p>' .strtoupper($str). '<p>;
}
}
Then you can simply call it in your Blade template like this:
@inject('helper', \App\Libraries\Helper)
{{ $helper->drawTimeSelector() }}
If you don't want to use @inject then just make the 'uppercasePara' function as static and embed the call in your Blade template like this:
{{ \App\Libraries\Helper::drawTimeSelector() }}
No need for aliases. Laravel resolves the concrete class automatically.