In this article, I will give you an example of the “Custom helper function in laravel“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.
What we will cover:
- Register Helper in composer.json
- Get data in controller using helper
- Get data in Blade File using helper.
we call all the category table data in the controller and blade file using a custom helper.
Create a folder and a file :
In this step, you need to create app/Helpers/helpers.php in your laravel project and put the following code in that file:
"autoload": {
"files": [
"app/Helper/Helpers.php"
],
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
]
},
Regenerate the list of all classes in the app, Hit this command in the terminal.
composer dump-autoload
Now we create a function in Helper\Helpers.php file to get the category data from the database using Category Model.
app\Helper\Helpers.php
<?php
namespace App\Helper;
use App\Model\Category;
class Helpers
{
#Get Category Data From Category Model
static function get_catdata()
{
$catdata = Category::get();
return $catdata;
}
}
?>
Now, we can call our function anywhere in the view and controller like this:
Get data in blade file using helper :
<table class="table">
@php
$catData = \App\Helper\Helpers::get_catdata()
@endphp
<thead>
<tr>
<th>S.no</th>
<th>Category Name</th>
</tr>
</thead>
<tbody>
@foreach($catData as $key => $data)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $data->name }}</td>
</tr>
</tbody>
@endforeach
</table>
Output :
Get data in controller using helper :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helper\Helpers;
class TestController extends Controller
{
public function categoryList()
{
$data = Helpers::get_catdata();
dd($data);
}
}
Output :
This article is originally published in : Custom helper function in laravel
Read Also : Change the date format in the blade file in Laravel.
Top comments (0)