16

Ok, in laravel 4, if I want to add my own custom class, eg : library\myFunction.php then I do the following steps :

  1. add "myFunctions.php" into app/library/myFunctiosn.php
  2. at app/start/global.php , within ClassLoader::addDirectories(array( , I add app_path().'/library',
  3. And to call it within my blade view, I add the following codes
<?php
  $FmyFunctions1 = new myFunctions;
  $is_ok1=($FmyFunctions1->is_ok());   
?>
  1. The contents of app/library/myFunctions.php is :
<?php namespace App\library {

    class myFunctions {
        public function is_ok() {
            return 'myFunction is OK';
        }
    }

}
?>

And it works.

But how to do so in Laravel 5 ???

PS : I read What are the best practices and best places for laravel 4 helpers or basic functions?

And tried to add "app/library/", to the autoload array and run composer dum-autoload , but it keeps give me error :

FatalErrorException in xxxx line xx: Class 'myFunctions' not found

I'm also already trying to use :

composer update
composer dump-autoload 
php artisan dump
php artisan clear-compiled
php artisan dump-autoload
php artisan optimize
php artisan route:clear
php artisan route:scan
php artisan route:list 

But still doesn't work...

Community
  • 1
  • 1
Galvion
  • 1,353
  • 7
  • 23
  • 35

2 Answers2

38

This should help you.

FYI: Basically, you could create another directory within app, and then namespace your files in there as appropriate:

app/CustomStuff/CustomDirectory/SomeClass.php.

Then, within your SomeClass.php, make sure you namespace it:

<?php 
namespace App\CustomStuff\CustomDirectory;

class Someclass {}

Now, you can access this class using the namespace within your classes:

use App\CustomStuff\CustomDirectory\SomeClass;
Captain Sparrow
  • 1,114
  • 17
  • 26
  • 4
    Filename & Class name should have the same name. – user2511140 Aug 18 '19 at 20:27
  • This is right, but you also need to add the folder to composer.json as specified in Amit's answer here https://stackoverflow.com/questions/41319341/class-not-found-when-using-custom-class – z3d0 Apr 27 '20 at 11:47
10

After some trial and error, I found the answer.

There is no need to modify Composer. Just modify the Blade into:

<?php
  $FmyFunctions1 = new \App\library\myFunctions;
  $is_ok = ($FmyFunctions1->is_ok());
?>
cyber-leech
  • 37
  • 2
  • 2
  • 9
Galvion
  • 1,353
  • 7
  • 23
  • 35