Implement Helper Functions in Laravel.

Implement Helper Functions in Laravel.

Helpers functions are very useful and effective in Laravel. It's main advantages is that they can be called from everywhere. I mean everywhere, its everywhere. You can call it from view , you can call from controller, everywhere. It can help in various ways like sendmail() function which can send mail. Another example could be active menu items for navbar.

Now let's see how to do it.

First, create a file named helpers.php in app\Helpers. You can now write any function on that file, which can be called from anywhere. But we are not done yet. Upto now we only made the file but Laravel doesn't know about it. So we have to register it to get autoloaded automatically. For that, we have to add some lines of codes in autoload section on the composer.json file at the root directory.

"autoload": {
        "files": [
            "app/Helpers/helpers.php"
        ],
        "psr-4": {
            .
            .
            .
        }
    },

Now run this command to regenerate the Laravel's optimized autoload files.

composer dump-autoload

Now you can go ahead and define your helpers functions. Remember to open a php tag <?php at the start. Here's one example to start with.

<?php
use Illuminate\Http\Request;

if (!function_exists('sendSimpleMail')) {
    function sendSimpleMail($to, $from_name, $from_address, $subject, $content)
    {
        Mail::send('emails.simplemail', ['content' => $content], function ($message) use ($to, $from_name, $from_address, $subject, $content) {
            $message->from($from_address, $from_name ? $from_name : env(APP_NAME));
            $message->subject($subject);
            $message->to($to);
        });
        return response()->json(['message' => 'Request completed']);
    }
}

This example function is used to send an simple email with the parameters provided. It's always a good idea to check if the function name already exists before defining it with function_exists() function.

And now you can use your helper functions wherever you want.

Happy Coding.