Mastering Global Functions in Laravel: Easy Methods for Versions 8,9,10,11.
Tags: laravel, php, programming, webdev
Published: 2024-04-04 18:15:16

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:


![laravel new command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4yd96r7jclrh6ne2re9n.png)

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. 


![Project setup in VSCode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4k9sswonpn07nln58kl5.png)

Serve the application and open on the browser:

```bash
php artisan serve
```

![bash](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqufn4enudw12hdniojg.png)



![Served application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc11ip85hmhx9t75p122.png)

## 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.



![tinker session](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qxplvlp612oy4ubfm69x.png)

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:

```bash
Total users: {{ $users }}
```
While on the web.php file, we do this:
```bash
<?php

use App\Models\User;
use Illuminate\Support\Facades\Route;

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

Our home page should look like this now:

![home page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c8flrkr0bzmtj92briug.png)

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`

```bash
php artisan make:provider GlobalFunctionsServiceProvider
```

This command creates a file on the App\Providers 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:

```bash
'providers' => ServiceProvider::defaultProviders()->merge([
        /*
         * Package Service Providers...
         */

        /*
         * 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\GlobalFunctionsServiceProvider::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 App\Functions\GlobalFunctions.php After that, open your GlobalFunctionsServiceProvider.php file and add the following code in the register method

```bash
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

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

```bash
<?php

use App\Models\User;

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

We can now remove the users key from our web.php routes file
```bash
<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});
```

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

```bash
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](https://github.com/frankliniwobi/mastering-global-functions-in-laravel).

Thank you. Happy coding.

You can [follow me on X(former twitter)](https://twitter.com/OkwudiliTweet) if you found this article helpful.