I'm trying to build a class with some frequently used functions that I can use from anywhere in my project. I don't know where to build the PHP file with the classes in it or how to recall them... Can anyone help me figure out where all this stuff fits in? THANKS!!!
/App/Http/Helpers/MyClasses.php
<?php
class PopularFunctions {
public function sayhi() {
echo 'hi';
}
}
?>
/App/Http/Controllers/TasksController.php
<?php
namespace App\Http\Controllers;
use App\Http\Helpers\MyClasses;
class TasksController extends Controller {
public function index() {
$myfunctions = new PopularFunctions();
$myfunctions->sayhi();
}
}
This returns: Class 'App\Http\Controllers\PopularFunctions' not found.
In Laravel Framework you can only create a controller inside the app\Http\Controller folder. If you want to create a custom class then created inside app folder.
<? php namespace App\User; class SomeClassName { ... }
Basically, we could create another directory within app
directory (MyCustomStuff
for example), and then namespace
our files correctly.
I know of two methods.
1. Global-Function Through Composer
App/MyCustomStuff/MyGlobalTools.php
<?php
function sayhi() {
echo 'hi';
}
?>
then in composer.json in "autoload": { }
add
"files": [
"app/MyCustomStuff/MyGlobalTools.php"
]
so the structure will be
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/MyCustomStuff/MyGlobalTools.php"
]
},
after you change the autoload. Then run composer dump-autoload
Then in controller, just call the global function (without need to import), like:
public function index() {
$res = sayHi();
}
2. Or Normal Class
App/MyCustomStuff/MyClass.php
<?php
namespace App\MyCustomStuff;
class MyClass {
function sayhi() {
echo 'hi';
}
}
?>
In your controller
<?php
namespace App\Http\Controllers;
use App\MyCustomStuff\MyClass;
class TasksController extends Controller {
public function index() {
$myfunctions = new MyClass();
$res = $myfunctions->sayhi();
}
}
create a directory say "Helpers" inside App/Http
create one class inside Helpers directory CustomAvatar.php
<?php
class CustomAvatar{
public $default_avatar='avatar.png';
public function make_custom_avatar(){
// do your operation here
}
}
?>
now if you want to use this class inside your controller :
use App\Http\Helpers\CustomAvatar;
...
public function create_user(){
$customAvatar=new CustomAvatar();
$defaultAvatar = $customAvatar->default_avatar;
$user=new User();
$user->avatar=$defaultAvatar;
$user->save();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With