To begin with, I would rather let the Laravel official site speak about helpers.
Laravel includes a variety of global "helper" PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.
So, basically, helpers in Laravel are built-in utility functions that you can call from anywhere within your application. If they hadn't been provided by the core framework, you might have ended up developing your own helper classes.
Although the core provides a variety of helpers already, there’s always a chance that you’ll need your own and would like to develop one so you don’t have to repeat the same code here and there, thus enforcing better maintainability. You'll learn how to create a custom Laravel helper in this tutorial.
Helpers in Laravel
As we discussed earlier, there are plenty of helpers available in the core of the Laravel framework. They are grouped together based on the functionality they provide. Here’s a list of helper groups.
Arrays
Helpers in this group provide functionality to manipulate array elements. More often than not, you're in the situation where you want to perform different operations on array elements. So this is the place where you should look first to see if what you're looking for already exists.
Paths
I find helpers in this category most useful. They return the fully qualified path of different directories like app, storage, config, and the like. I bet you're using most of these helpers already in your Laravel application.
Strings
String manipulation is something inevitable in your day-to-day application development. Although there are plenty of string manipulation functions provided by PHP itself, you'll find a few more useful goodies in this section.
URLs
You'll find very few in this category, but they are used throughout the application. They are used to generate route, asset, and form action URLs.
Miscellaneous
This category contains helpers that provide a variety of functionalities ranging from logging to debugging and many more.
For a complete reference of Laravel helpers, there's no better place than the official documentation.
Create Your First Custom Helper
Now you have a basic understanding of Laravel helpers and what they are used for. In this section, I’ll go ahead and demonstrate how you can create your own custom helper that can be used globally in your Laravel application.
To keep things simple and easy to understand, it’ll be a pretty basic helper that takes a userid and returns a username as a response. Of course, that doesn’t sound fancy, but I believe it’s enough to demonstrate the concept, and you could always extend it to fulfill your complex requirements.
I assume that you have a users table in your database and it has at least two fields—userid and username.
The Skeleton of a Laravel Helper
Before we move ahead and actually create the files, let’s have a quick look at the files that we’re going to create in the rest of the article.
app/Helpers/Envato/User.php
: It’s our helper file that holds the logic of our helper.app/Providers/EnvatoServiceProvider.php
: It’s a custom service provider file that loads our custom helper file.config/app.php
: In this file, we’ll declare our custom service provider, and it also helps us to define an alias to our helper so that we don’t have to use the fully qualified class name of our helper.routes/web.php
: A pretty standard Laravel route file where we’ll actually test our helper.
Create Helper Files
Although you could place your helper files anywhere in your application, the more intuitive and standard way suggests that it should go under your app
directory.
So go ahead and create a Helpers/Envato
directory under app
and create a User.php
file with the following contents. Of course, you could place it directly under the app
or app/Helpers
directory, but providing that extra level allows us to organize our helpers in good shape, specifically when you’re going to have plenty of them.
<?php //app/Helpers/Envato/User.php namespace App\Helpers\Envato; use Illuminate\Support\Facades\DB; class User { /** * @param int $user_id User-id * * @return string */ public static function get_username($user_id) { $user = DB::table('users')->where('userid', $user_id)->first(); return (isset($user->username) ? $user->username : ''); } }
The file starts with a pretty standard namespace declaration:
namespace App\Helpers\Envato;
The purpose of our custom helper is to retrieve a username based on a userid. Hence, we need to interact with the database, and that forces us to include DB Facade.
use Illuminate\Support\Facades\DB;
For those who are not familiar with Laravel Facades, it’s just another convenient way to access the objects in service containers. Alternatively, you could have used dependency injection.
Moving ahead, there comes the concrete implementation of our helper. As you can see, there’s a static method that defines the logic of retrieving a username based on a userid.
$user = DB::table('users')->where('userid', $user_id)->first();
The $user
object holds the database record with the matching userid. Finally, the method returns the username as a response in the following statement.
return (isset($user->username) ? $user->username : '');
That’s it as far as our helper file is concerned.
Now we’ve created our helper file, but the question is how are you going to use it? Two quick solutions come to my mind:
- You can include our helper filename in the
composer.json
, so that it gets auto-loaded. Then, you could straight away call the static method of our helper class. - You can go ahead and create a Laravel service provider that allows you to register your custom helper file so that the Laravel framework loads it along with other dependencies. Register that service provider in the Laravel configuration and create an alias to use your helper.
Of course, the first one is pretty quick and easy to implement, and you might be tempted to do so, but I would rather suggest the latter one as it looks like more of an artisan way and is more maintainable.
Move to the command line and run the following command in your application root to create a new service provider.
$php artisan make:provider EnvatoServiceProvider Provider created successfully.
You should see the message that confirms that it’s created successfully under the app/Providers
directory.
Open that file and you should already see two methods out there. The important one in the context of this article is the register
method. Yes, it’s empty at the moment, so let’s feed in some stuff to make it more useful.
public function register() { require_once app_path() . '/Helpers/Envato/User.php'; }
The register method is used to register your dependencies, and we’ve exactly done that. We’ve included our custom helper file.
Here’s how the app/Providers/EnvatoServiceProvider.php
file should look after modifications.
<?php // app/Providers/EnvatoServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; class EnvatoServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { require_once app_path() . '/Helpers/Envato/User.php'; } }
So it’s all pretty good so far. We have our custom helper and service provider on the table.
Next, we need to inform Laravel about our service provider so that it can load it during bootstrapping. Let’s open the config/app.php
and add the following entry in the providers
array at the end.
App\Providers\EnvatoServiceProvider::class,
To use our helper in a convenient way, we could create an alias as well. So let’s do that by adding the following entry in the aliases
array at the end in the same file.
'EnvatoUser' => App\Helpers\Envato\User::class,
By defining this entry, we can call our helper by using the EnvatoUser
keyword. Pretty convenient, huh? For your reference, here’s the complete config/app.php
file.
<?php // config/app.php return [ /* |-------------------------------------------------------------------------- | Application Name |-------------------------------------------------------------------------- | | This value is the name of your application. This value is used when the | framework needs to place the application's name in a notification or | any other location as required by the application or its packages. */ 'name' => 'Laravel', /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services your application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Logging Configuration |-------------------------------------------------------------------------- | | Here you may configure the log settings for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Settings: "single", "daily", "syslog", "errorlog" | */ 'log' => env('APP_LOG', 'single'), 'log_level' => env('APP_LOG_LEVEL', 'debug'), /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Notifications\NotificationServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Package Service Providers... */ Laravel\Tinker\TinkerServiceProvider::class, /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, App\Providers\EnvatoServiceProvider::class, ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Broadcast' => Illuminate\Support\Facades\Broadcast::class, 'Bus' => Illuminate\Support\Facades\Bus::class, 'Cache' => Illuminate\Support\Facades\Cache::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Notification' => Illuminate\Support\Facades\Notification::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, 'Schema' => Illuminate\Support\Facades\Schema::class, 'Session' => Illuminate\Support\Facades\Session::class, 'Storage' => Illuminate\Support\Facades\Storage::class, 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, 'EnvatoUser' => App\Helpers\Envato\User::class, ], ];
We’re almost there! We’ve done all the hard work to get here, and now we can reap the benefits of our custom helper.
Your First Custom Helper in Action
Again, to keep things simple and straightforward, we’ll define a basic Laravel route and call our helper from there!
Go ahead and create a routes/web.php
file with the following contents.
<?php // routes/web.php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/envato-user-helper-demo', function () { return EnvatoUser::get_username(1); });
Does that need any explanation at all? We’ve just called the custom helper by the shorthand EnvatoUser::get_username
, and it should return the username.
Of course, you can call our helper from anywhere in the application, be it a controller or view.
So that ends our story for today.
Conclusion
Helpers in Laravel are really a powerful feature, and I'm sure that as a developer you would love to extend that. And that was the topic of today—we went through the basics of the Laravel helper file structure and created a useful custom helper.
I hope you’ve enjoyed the article and it helps you create your own custom helpers in day-to-day Laravel application development.
Don’t hesitate to leave your comments and queries in the feed below. I also catch comments on my Twitter and respond to them as soon as I can!
No comments:
Post a Comment