How To Create Custom Helper In Laravel 5.5

Today in this article we are share with you how to make custom helper in laravel. you need some time make your own custom helper for some repeted code or logic. like get fullname of current user. convert currency helper, number formate etc...

So, you can create above all logic in one time in one helper function then you can use this custom helper function in everywere in laravel application. you use this custom helper in your laravel blade file and also use in any controller.

in this article we are make one custom helper which get current user full name and how to use this custom helper in blade file and laraval controller.

Please follow step to create custom helper in laravel application

Step : 1 Create app/helpers.php file

First, we are create one helper class file in app/helpers.php path and in this file we are write our any custom helper logic into the function.

Right now in this file we are write one function in this function we are pass current user ID and function return to full username. this is very basic idea then you can create any custom function as per your requirement.


<?php

function getUserFullName($id) {
	$data = \DB::table('users')
        ->select(\DB::raw('CONCAT(firstname, " ", lastname) as username'))
        ->where('id', $id)
        ->first();

    return $data->username;
}
	
Step : 2 Add app/helpers.php file in composer.json file

Now, we are add our app/helpers.php file in composer.json file for a autoload section.


"autoload": {
    "classmap": [
        ...
    ],

    "psr-4": {
        "App\\": "app/"
    },

    "files": [
        "app/helpers.php" //Add This Line
    ]
},
	

After done this then once we are run following command.


composer dump-autoload
	

Now, we are showing how to use this custom helper in controller as well as laravel blade file

Step : 3 How To Use Custom Helper In Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class HomeController extends Controller
{   
    
    public function index()
    {
        $fullusername = getUserFullName(Auth::user()->id);
        dd($fullusername);
    }

}
	
Step : 4 How To Use Custom Helper In Blade File

@extends('layouts.app')

@section('content')

<?php
	$fullusername = getUserFullName(Auth::user()->id);
    dd($fullusername);
?>

@endsection
	

We are hope you like this tutorials, if any question regarding any query please post your question in our forums click on bellow link Laravelcode's Forums

 Prev post

Next post