phplaravel

How to call custom helper in laravel 5?


I wanna make my very own helper, and i put it in app/http/helpers.php. This is my helper code:

<?php

namespace App\Helpers;
use Auth;
class helper {

    public static function is_login() {
        if(Auth::check()){
           return True;
        }else{
           return False;
        }
    }

    public static function must_login(){
        if(Auth::check()){
           return True;
        }else{
           return Redirect::to('logout');;
        }
    }
}

?>

and this is my app.php code:

  'aliases' => [
                'customhelper'=> App\Helpers\Helper::class
               ]

when i use for my blade file customhelper::is_login() it work. But when i try to use in my controller customhelper::must_login() it doesn't work and i've got some error

Class 'App\Http\Controllers\customhelper' not found


Solution

  • Use your alias with the same name of Helper Class and add use statement to Controller file.

    For Example :

    app/Helpers/Helper.php

    <?php
    namespace App\Helpers;
    
    class Helper{
        public static function sayHello()
        {
            return "sayHello";
        }
    }
    

    config/app.php

    'aliases' => [
        /*Defaults...*/
        'Helper' => App\Helpers\Helper::class, 
    ],
    

    app/Http/Controllers/MyController.php

    namespace App\Http\Controllers;
    
    use App\Http\Controllers\Controller;
    
    use Helper; // Important
    
    class MyController extends Controller
    {
        public function index()
        {
            return Helper::sayHello();
        }
    }