In this article, We will discuss how to create a custom helper file and use in Laravel 9(Laravel 9 Create Custom Helper File Example). laravel provides lot’s up functionality but sometimes we need to custom functionality for our project or task. we will take the latest example and learn how to create laravel 9 custom helper function.
So let’s follow the below step for create a custom helper function.
Step1: Create the helper file.
first, we will create a helper file in the “your-project-directory/app/helper.php”. put some code in this file. here this file we use the dynamic table with where condition. because we need the category name according to the product category id. so finally, we will get the category name using the custom helper function.
<?php if(!function_exists('getTableWhere')) { function getTableWhere($table,$where) { $data = \DB::table($table) ->select(\DB::raw('*')) ->where($where) ->first(); return $data; } } ?>
Step2: Add helper file in the composer.json file.
Now, we will add the path in the composer.json file at autoload array section.
"autoload": { "files": [ "app/helper.php" ],
After the above changes, we will run the following command.
composer dump-autoload
Step3: How to use the custom helper function in Controller or Views.
now, we can use the custom helper function in Controller or Views. we can get the categories name in Controller or Views using the call getTableWhere helper function and pass parameter.
Controller Example
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ProductController extends Controller { public function index() { $where= array('id'=>$product->product_category_id); $data = getTableWhere('categories',$where); echo "<pre>"; print_r($data); echo "</pre>"; die; return view('product.view', compact('result','data')); } } ?>
View Example
@php $where= array('id'=>$product->product_category_id); $data = getTableWhere('categories',$where); {{ $data->title }} @endphp
So finally, I hope you like this article.