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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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

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.

Questions:
Answers:

you can add this in your laravel blade file

<?php  use MyApp\YourCustomClass; ?>