Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use my custom class in a view on Laravel 5

I have a custom class that I have to use inside my view. But how I do this?

In Laravel 4.2, I simply run composer.phar dump-autoload and add in start/local.php as follow:

ClassLoader::addDirectories(array(
    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/helpers/MyClass',
));

Finally, inside my view, I just use my class: MyClass::myMethod(). Again, how I do this with Laravel 5?

Thanks

like image 857
humungs Avatar asked Feb 06 '15 17:02

humungs


1 Answers

You have two options, make a Service or a Service Provider.

Service

This class could works as a helper having all its methods statics. For example, in app/Services folder you can create a new one:

<?php
namespace Myapp\Services;

class DateHelper{
 
    public static function niceFormat(){
        return "This is a nice format";
    }

}

Then, add an alias to this class at config/app.php like so:

'DateHelper' => 'Myapp\Services\DateHelper'

Now, In your application you can call the niceFormat() method like \DateFormat::niceFormat();

Service Provider

In the other hand, you can create a Service Provider like the docs state and attach a Facade.

like image 187
manix Avatar answered Sep 20 '22 20:09

manix