Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5.2 create common function for controllers? must use helper?

i want to create a functions which can be called by all controllers

public function getSuffix($filename) {

    $first_char = substr($filename, 0 ,1);
    $sec_char = substr($filename, 1 ,1);
    $suffix ="";

    if($first_char!='.' && $first_char!='..')
        $suffix .= '/'.$first_char.'/';
    if($sec_char!='.' && $sec_char!='..')
        $suffix .= $sec_char.'/';

    return $suffix;
}

what is the best practice for doing this? Is helper class what i'm searching?

like image 377
hkguile Avatar asked Dec 24 '22 06:12

hkguile


2 Answers

create a helpers.php file inside app/http folder. then your composer.json file autoload this file .

"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/Http/helpers.php"
        ]
    },

then run composer dump-autoload your problem is solved

like image 178
tapos ghosh Avatar answered Apr 08 '23 00:04

tapos ghosh


First you need to create folder in app like CustomFolder and create you helper class in custom folder like SimpleClass.php

<?php
namespace App\CustomFolder;
class SimpleClass {

public function yourFunction(){
   return true;
} 

}

?>

when you use this helper class in your controller simple add namespace like

<?php

use App\CustomFolder\SimpleClass;
class MyController extends Controller{

}

?>

I think your helper class work perfectly.

like image 41
Taulut Hossain Washi Avatar answered Apr 08 '23 00:04

Taulut Hossain Washi