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

2
  • 1
    Did you use use statement in your controller? Commented Apr 3, 2017 at 8:39
  • have you treid composer dump-autoload Commented Apr 3, 2017 at 8:39

2 Answers 2

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Correct the naming conventions - sayHello instead of SayHello
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.