DEV Community

Cover image for Mastering Global Functions in Laravel: Easy Methods for Versions 8,9,10,11.
Iwobi Okwudili Frank
Iwobi Okwudili Frank

Posted on

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:

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

Project setup in VSCode

Serve the application and open on the browser:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

bash

Served application

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

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 }}
Enter fullscreen mode Exit fullscreen mode

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

<?php

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

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

Our home page should look like this now:

home page

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
Enter fullscreen mode Exit fullscreen mode

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:

'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(),
Enter fullscreen mode Exit fullscreen mode

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

<?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
    {
        //
    }
}
Enter fullscreen mode Exit fullscreen mode

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

<?php

use App\Models\User;

function users_count()
{
    return User::count();
}
Enter fullscreen mode Exit fullscreen mode

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

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});
Enter fullscreen mode Exit fullscreen mode

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

Total users: {{ users_count() }}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (3)

Collapse
 
ugochukwuj16059 profile image
Joy Ugochukwu

Thank you so much for this. It was really insightful.

Collapse
 
collinsonine profile image
Collins Onine

This makes it so simple, thank you so much.

Collapse
 
frankliniwobi profile image
Iwobi Okwudili Frank

I'm happy you found it helpful 🙂