DEV Community

Cover image for Laravel 8: Create a Custom Helper Function
8bityard
8bityard

Posted on

Laravel 8: Create a Custom Helper Function

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:

  1. Register Helper in composer.json
  2. Get data in controller using helper
  3. Get data in Blade File using helper.

we call all the category table data in the controller and blade file using a custom helper.

laravel custom helper function

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:

helper register in laravel

 "autoload": {
         "files": [
            "app/Helper/Helpers.php"
        ],

        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },

Enter fullscreen mode Exit fullscreen mode

Regenerate the list of all classes in the app, Hit this command in the terminal.

composer dump-autoload
Enter fullscreen mode Exit fullscreen mode

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;
    }
  }

  ?>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Output :

helper data in blade file

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);
   }
 }
Enter fullscreen mode Exit fullscreen mode

Output :

get helper data in controller

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)