2

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

Reynald Henryleo
  • 397
  • 2
  • 7
  • 22

2 Answers2

11

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();
    }
}
aprogrammer
  • 1,764
  • 1
  • 10
  • 20
1

@Reynald Henryleo

First thing like you have mentioned 'app/http/helpers.php' your helper file path in that case your namespace should be 'namespace App\Http'.

for better understanding to make global helper function refer 'Custom Classes in Laravel 5, the Easy Way' section of Best practices for custom helpers on Laravel 5

Community
  • 1
  • 1