Mastering Global Functions in Laravel: Easy Methods for Versions 8,9,10,11.

Mastering Global Functions in Laravel: Easy Methods for Versions 8,9,10,11.

If you’ve ever found yourself seeking for efficient ways to have global functions in your Laravel apps you’re in the right place. Global functions offer a convenient way to enhance the functionality and productivity of your Laravel apps as you only have to write a function once and have access to it in any part of your app, in this comprehensive tutorial, we’ll explore the easiest methods to achieve this. Whether you’re a seasoned Laravel developer or just starting your journey, this guide will equip you with the knowledge and tools to leverage global functions effectively, making your development experience smoother and more efficient. Let’s dive in!

For this example, we’ll be displaying the user count on different pages, it may not a very good example but it would give you an idea on how to implement such functionality in you own app. Let’s dive in!

Get your Laravel App running.

In this step we will install a fresh Laravel project using the Laravel installer, you can also use composer or any other means you use to get your Laravel applications up and running.

As at the time of writing this post, Laravel is on version 11. You have to make sure you have a PHP version of at least 8.2. We will now create a Laravel project with the new command:

I would not be using any starter kit for this example.

After installation, let’s open the project on our code editor, I’m using Virtual Studio Code.

Serve the application and open on the browser:

php artisan serve

Let’s get to the main job!

Now that our Laravel app is running, we can now start writing code. For the sake of this example, I’ll populate the database with 35 users using the default UserFactory that comes with every Laravel installation. I’ll use tinker for ease.

After that let’s first display the users count on the home page, let’s delete everything on the welcome.blade.php file and write this:

Total users: {{ $users }}

While on the web.php file, we do this:

<?php

use AppModelsUser;
use IlluminateSupportFacadesRoute;

Route::get(‘/’, function () {
return view(‘welcome’, [
‘users’ => User::count()
]);
});

Our home page should look like this now:

We can now see that if we want to see a count of users on different pages we would have to repeat this line of code on both the view file and route file, this is a lot of work. Let’s create a Global Function. There are so many ways to create a global function in Laravel but the best way is using a Service Provider. We’ll create it through the terminal, you can name it what ever you want but I’ll call mine GlobalFunctionsServiceProvider

php artisan make:provider GlobalFunctionsServiceProvider

This command creates a file on the AppProviders directory. Note that in Laravel 11, you do not need to register this provider in the app.php providers array since it is auto-discovered by Laravel but if you’re using a lower version of Laravel you would need to do so. Just open the Config/app.php file and add it to the providers array like this:

‘providers’ => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers…
*/

/*
* Application Service Providers…
*/
AppProvidersAppServiceProvider::class,
AppProvidersAuthServiceProvider::class,
// AppProvidersBroadcastServiceProvider::class,
AppProvidersEventServiceProvider::class,
AppProvidersRouteServiceProvider::class,
AppProvidersGlobalFunctionsServiceProvider::class, //our custom provider
])->toArray(),

Note: You do not need the above step if you’re in Laravel 11

Now let’s create a file to store our functions, I’ll create mine in AppFunctionsGlobalFunctions.php After that, open your GlobalFunctionsServiceProvider.php file and add the following code in the register method

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;

class GlobalFunctionsServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
require_once base_path().‘/app/Functions/GlobalFunctions.php’;
//remeber to point to the path of the file where your functions are
}

/**
* Bootstrap services.
*/
public function boot(): void
{
//
}
}

Now let’s write our global function. Open your GlobalFunctions.php file and write the following code

<?php

use AppModelsUser;

function users_count()
{
return User::count();
}

We can now remove the users key from our web.php routes file

<?php

use IlluminateSupportFacadesRoute;

Route::get(‘/’, function () {
return view(‘welcome’);
});

And edit our welcome.blade.php file to use the function we wrote earlier

Total users: {{ users_count() }}

You can see now that we have the same result on the browser! With this approach, you can call the users_count() function from any part of your application, whether view, controller, class, config files, anywhere, and be certain to get the same result.

You can customize the code to fit your use case, this was just an example.

The source code for this example is on this Github repo.

Thank you. Happy coding.

You can follow me on X(former twitter) if you found this article helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *