Create Custom Helper In Laravel
Laravel includes a variety of global “helper” PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.
In this article, we are going to learn how to make custom helper in Laravel. We can define many custom functions in the helper and can use those functions in anywhere we want.
Let’s follow these steps to create a custom helper:
Table of Contents
Step 1 : Create helpers.php File
Navigate to app/Http folder and create a file called “helpers.php‘. Open the file. Let’s create a simple function to get a specific user data.
<?php
function getUserData($id)
{
$data = DB::table('users')
->where('id', $id)
->first();
return array('response' => true, 'data' => $data);
}
Step 2 : Define helpers in composer.json
Open the composer.json file and in the autoload section we need to define the location of helpers.php. Here’s the example:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/Http/helpers.php"
]
},
After adding the helpers.php, run this command to load the file globally in our project:
composer dump-autoload
Step 3 : Use in Controller
We have created the custom helper. Let’s call it in a controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Response;
class TestController extends Controller
{
public function index()
{
$user_id = Auth::user()->id;
$user = getUserData($user_id);
return Response::json($user);
}
}
If we visit this route, the output will look like:
Step 4 : Use in Blade File
Like controller, we can also use helper in blade file. Here’s an example:
@extends('layouts.app')
@section('content')
<?php
$user = getUserData(Auth::user()->id);
dd($user);
?>
@endsection
We have created and tested custom helper. Thank you.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.