Custom helper classes in Laravel 5.4 [duplicate] - php

This question already has answers here:
How to create custom helper functions in Laravel
(23 answers)
Closed 7 months ago.
I have some helper classes in app/Helpers. How do I load these classes using a service provider to use them in blade templates?
e.g. If I have a class CustomHelper that contains a method fooBar() :
<?php
nampespace App\Helpers;
class CustomHelper
{
static function fooBar()
{
return 'it works!';
}
}
I want to be able to do something like this in my blade templates:
{{ fooBar() }}
instead of doing this:
{{ \App\Helpers\CustomHelper::fooBar() }}
P.S: #andrew-brown's answer in Best practices for custom helpers on Laravel 5 deals with non-class files. It would be nice to have a class based solution so that the helper functions can be organized among classes.

I don't think it's possible to use only function when you have code in your classes. Well, you could try with extending Blade but it's too much.
What you should do is creating one extra file, for example app\Helpers\helpers.php and in your composer.json file put:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": ["app/Helpers/helpers.php"] // <- this line was added
},
create app/Helpers/helpers.php file and run
composer dump-autoload
Now in your app/Helpers/helpers.php file you could add those custom functions for example like this:
if (! function_exists('fooBar')) {
function fooBar()
{
return \App\Helpers\CustomHelper::fooBar();
}
}
so you define global functions but in fact all of them might use specific public methods from some classes.
By the way this is exactly what Laravel does for its own helpers for example:
if (! function_exists('array_add')) {
function array_add($array, $key, $value)
{
return Arr::add($array, $key, $value);
}
}
as you see array_add is only shorter (or maybe less verbose) way of writing Arr::add

Related

How to make a global variable for all blade laravel

Good Peoples.
I have an issue with my project.
In the layout blade, I need to fetch some data from the database. But I cannot pass variables as there has no route for the layout blade. It's just a master blade.
Is there any way to make a global variable and use it all blade?
Thanks for the valuable replies.
to have global functions or variables there are different ways
in my opinion, the easiest way is:
make a helper php file to restore global functions and vars, in this way you
load this file in composer.json and you can call that everywhere you want.
I created Functions.php in App/Helpers directory to restore my global vars and functions.
after that declare the file in composer.json:
"autoload", inside it if there is not "files(array)" add it and set the path to
your file. in my example, it is "app/Helpers/Functions.php".
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/Helpers/Functions.php"
]
},
finally, rerun the
php artisan serve
for accessing a variable in your blade, I'm not sure you can do it or not (I tried but it returns undefined variable).
you can do:
// in your helper file
myFunc() {
$myVar = 'value';
return $myVar;
}
// in your blade
{{ myFunc() }}
or using classes:
// in your helper file
class myClass {
protected $myVar = 'value';
protected static $staticVar = 'value';
public myFunc() {
return $this->myVar;
}
public static staticFunc() {
return myClass::$staticVar;
}
}
// in your blade
{{ (new myClass())->myFunc() }}
// of static function
{{ myClass::staticFunc() }}
hope, it helps...
you can use laravel helpers to declare a global variable, you can create your own customize helper function.
you can follow laravel custom helpers and this one to custom create helpers
Create a new Service Provider as suggested in here
Add your new Service Provider to the configuration file (config/app.php).
In the boot method of your new Service Provider use:
View::share( 'something_cool', 'this is a cool shared variable' );
Now you are ready to use $something_cool in all of your views.

How to call a controller function inside a view in laravel 5

In laravel 4 i just used a function
$varbl = App::make("ControllerName")->FunctionName($params);
to call a controller function from a my balde template(view page).
Now i'm using Laravel 5 to do a new project and i tried this method to call a controller function from my blade template .But its not working and showing some errors.
Is there any method to call a controller function from a view page in Laravel 5?
Just try this in your view :
{{ ControllerName::Functionname($params); }}
OR
<?php echo ControllerName::Functionname($params);?>
Refer this : http://laravel.io/forum/03-06-2014-what-is-the-proper-way-to-call-controllers-from-the-view?page=1
If you have a function which is being used at multiple places you should define it in helpers file, to do so create one (may be) in app/Http/Helpers folder and name it helpers.php, mention this file in the autoload block of your composer.json in following way :
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Http/Helpers/helpers.php"
]
},
run composer dump-autoload, and then you may call this function from anywhere, let it be controller view or model.
or if you don't need to put in the helpers. You can just simply call it from it's controller. Just make it a static function.
Create.
public static function funtion_name($args) {}
Call.
\App\Http\Controllers\ControllerName::function_name($args)
If you don't like the very long code, you can just make it
ControllerName::function_name($args)
but don't forget to call it from the top of the view page.
use \App\Http\Controllers\ControllerName;
In laravel 5, you can do it like so
In your view:
<?php use App\Http\Controllers\ControllerName;
echo ControllerName::functionName(); ?>
The functionName should have the 'static' keyword e.g
Controller function:
public static function functionName() {
return "Hello World!";
}
You can actually call a class, helper class or any declared class in your blade template but putting it in the aliases array of your app.php in the config folder
'Helper' => App\Http\Helpers\Helper::class,
Using the Helper as an alias, you can reference it in your blade template, example below:
{{Helper::formatDateToAgo ($notification->created_at)}}
For accessing a method of a Controller from a view page you need to give the full path of that controller in your blade page.
use App\Http\Controllers\AdminAfterAuth;
$admin_dtls = AdminAfterAuth::globAdmin();
Here AdminAfterAuth is the controller class name and globAdmin is the method name.
Now in your controller declare the method statically.
public static function globAdmin(){
$admin_val = AdminLogin::where('id',session('admin_id'))->get();
return $admin_val;
}
In view call the function like this:
#php
use App\Http\Controllers\ControllerName;
$var = ControllerName::FunctionName();
#endphp
But if the function name in the controller is as:
public function FunctionName(){
return something;
}
Then an error will be shown:
Non-static method App\Http\Controllers\ControllerName::FunctionName() should not be called statically(...)
So to solve this problem "non-static" you have to change your function like this:
public static function FunctionName(){
return something;
}
Then you are all done.
I like and favor Khan Shahrukh way, it is better to create a helpers files with all your functions, then add it to your composer.json file:
"autoload": {
"files": [
"app/Http/Helpers/helpers.php"
]
},
You can select the path that suits you, then dump-autoload composer to make it includes the new file.
For usability and clean work, after that you will be able to invoke your function on any view file OR project parts : Controller, Model.
If you decided to go with the public static method Don't forget to add this line at the very top of your view:
use \App\Http\Controllers\ControllerName;
In my blade view (Laravel), I used below blade syntax (specify full path) to call my controller action.
{{ App\Http\Controllers\mynestedpageController::index() }}
Controllers methods are not supposed to be called from the view. Best options are to call the method from the method which is returning the view object, which contains the output which you then can echo in the view;
public function bar() {
$foo = $this->foo();
return view( 'my.view', compact( 'foo' ) );
}
protected method foo()
{
return 'foobar';
}
second option to add a helpers file to the compose.json file
"autoload": {
"files": [
"app/helpers.php"
]
},
dump your autoload and you can call these functions from anywhere inside your application
Actually below should work as per Laravel 5:
Usage: App::make(ControllerName)->functionName($parameters);
Example: App:make("TestController")->getUserInfo('user_id' => 9);
Please post the actual error you are getting!

How do I make global helper functions in laravel 5? [duplicate]

This question already has answers here:
How to create custom helper functions in Laravel
(23 answers)
Closed 7 months ago.
If I wanted to make a currentUser() function for some oauth stuff I am doing where I can use it in a view or in a controller (think rails, where you do helper_method: current_user in the application controller).
Everything I read states to create a helpers folder and add the function there and then that way you can do Helpers::functionName Is this the right way to do this?
Whats the "laravel way" of creating helper functions that can be used in blade templates and controllers?
Create a new file in your app/Helpers directory name it AnythingHelper.php
An example of my helper is :
<?php
function getDomesticCities()
{
$result = \App\Package::where('type', '=', 'domestic')
->groupBy('from_city')
->get(['from_city']);
return $result;
}
generate a service provider for your helper by following command
php artisan make:provider HelperServiceProvider
in the register function of your newly generated HelperServiceProvider.php add following code
require_once app_path('Helpers/AnythingHelper.php');
now in your config/app.php load this service provider and you are done
'App\Providers\HelperServiceProvider',
An easy and efficient way of creating a global functions file is to autoload it directly from Composer. The autoload section of composer accepts a files array that is automatically loaded.
Create a functions.php file wherever you like. In this example, we are going to create in inside app/Helpers.
Add your functions, but do not add a class or namespace.
<?php
function global_function_example($str)
{
return 'A Global Function with '. $str;
}
In composer.json inside the autoload section add the following line:
"files": ["app/Helpers/functions.php"]
Example for Laravel 5:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": ["app/Helpers/functions.php"] // <-- Add this line
},
Run composer dump-autoload
Done! You may now access global_function_example('hello world') form any part of your application including Blade views.
Laravel global helpers
Often you will find your self in need of a utility function that is access globally throughout you entire application. Borrowing from how laravel writes their default helpers you're able to extend the ability with your custom functions.
Create the helper file, not class
I prefer to you a file and not a class since I dont want to bother with namespaces and I want its functions to be accessible without the class prefixes like: greeting('Brian'); instead of Helper::greeting('Brian'); just like Laravel does with their helpers.
File: app/Support/helper.php
Register helper file with Composer: composer.json
{
...
"autoload": {
"classmap": [
"database"
],
"files": [
"app/Support/helpers.php"
],
"psr-4": {
"App\\": "app/"
}
},
...
}
Create your first helper function
<?php
if (!function_exists('greet')) {
/**
* Greeting a person
*
* #param string $person Name
* #return string
*/
function greet($person)
{
return 'Hello ' . $person;
}
}
Usage:
Remember to autoload the file before trying to access its functions:
composer dump-autoload
Let's test with Tinker
$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.0.6 ΓÇö cli) by Justin Hileman
>>> greet('Brian');
=> "Hello Brian"
>>> exit
Exit: Goodbye.
With Blade
<p>{{ greet('Brian') }}</p>
Advanced usage as Blade directive:
A times you will find yourself wanting to use a blade directive instead of a plain function.
Register you Blade directive in the boot method of AppServiceProvider: app/Providers/AppServiceProvider.php
public function boot()
{
// ...
Blade::directive('greet', function ($expression) {
return "<?php echo greet({$expression}); ?>";
});
}
Usage:
<p>#greet('Brian')</p>
Note: you might need to clear cache views
php artisan view:clear
The above answers are great with a slight complication, therefore this answer exists.
utils.php
if (!function_exists('printHello')) {
function printHello()
{
return "Hello world!";
}
}
in app/Providers/AppServiceProvider.php add the following in register method
public function register()
{
require_once __DIR__ . "/path/to/utils.php"
}
now printHello function is accessible anywhere in code-base just as any other laravel global functions.
Another option, if you don't want to register all your helper functions one by one and wondering how to register them each time you create a new helper function:
Again in the app/Providers/AppServiceProvider.php add the following in register method
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename) {
require_once($filename);
}
}

Include a file in laravel controller?

I am creating a project with some additional functionality provided in form of a .php file API which contains some functions and some classes(out of which some class names are conflicting with Laravel built in class names) so, my question how should I include this file in my Laravel Controller to call functions in the file which using the classes of the file without referring Laravel classes and with less or no modification in .php API file?
Note* I am using Laravel-5.1
If you have a custom file containing some classes/functions that need to be loaded for every request, you need to make sure it's added to the autoloader.
In your composer.json add the following in your autoload section:
"autoload": {
"files": [
"path/to/your/File.php"
]
}
This will make sure the file is loaded. Now what you need is a way to use those classes without conflicting with existing Laravel classes.
First, make sure you have a namespace declaration at the top of your included file - say namespace Your\Namespace. In order to avoid conflicts, you need to explicitly tell PHP which class you mean when you reference it in the code. You mentioned your file contains a Response class that also exists in Laravel. In order to be able to use both, you need to alias one of them:
use Illuminate\Http\Response as LaravelResponse;
use Your\Namespace\Response;
Now in your code you can refer to Laravel's Response class as LaravelResponse, and to your response by simply Response.
Location of the file is irrelevant, as long as it's in a folder accessible to Laravel and its patch is added to composer.json.
Keep in mind that storing multiple classes per file is discouraged as a bad practice. I strongly suggest that you split your fine into separate file per class + one additional file with global functions.
Make an alias
Ex.
use App\Http\Requests\Request as DifferentRequest;
DifferentRequest->doStuff();
Aliasing/Importing
make an alias as #user2504370 proposed,
add to the composer:
"autoload": {
"classmap": [
"database",
"place_with_your_file",
],
"psr-4": {
"App\\": "app/",
"your_namespace": "your path",
}
},
and run
composer dump-autoload
EDIT:
there was a typo in classmap. I wanted to tell you you can put your file whenever you want, for example, you can create a new folder 'place_with_your_file', which is not necessarily inside Laravel's folder.
I'm using it with my external libraries.
For PSR-4: if you are using namespaces, then here you will register the base namespace and the folder where can be found:
for example: "Utilities\\": "../utilities/app"
or whichever your path is.
and for classmap, you need to include path to this folder:
"../utilities/app"
and your autoload will look something like this:
"autoload": {
"classmap": [
"database",
"../utilities/app",
],
"psr-4": {
"App\\": "app/",
"Utilities\\": "../utilities/app"`
}
},
Thank you all for taking efforts in trying to solve my problem but none of the solution worked for me so, here is what I tried for my problem
Below is the structure of my php file that I wanted to includes/integrate
<?php
class Misc {
const SUCCESS = 1;
const FAILURE = 0;
public static function get_hash ( $key )
{
...
...
...
}
public static function show_reponse ( $result )
{
...
}
}
function check($keyhash)
{
...
...
...
}
function function2()
{
...
...
...
}
class Response {
public function __construct ( $key )
{
...
}
public function __destruct ()
{
unset( $this->key );
unset( $this->params );
}
public function __set ( $key)
{
...
}
public function __get ( $key )
{
return $this->params[$key];
}
private function check_now ()
{
...
}
}
The main problem I was facing is the class name Response which was conflicting with Laravel Response class so I just removed all classes from the file and moved to their individual files in a new folder in Laravel\App folder and added namespaces to all classes.
Then I moved all functions in a PHP file in laravel\App directory
and used classnames along with the namespace defined and since I moved all functions in a different PHP file I could easily call the functions
so here is my final folder structure of Laravel
Laravel
-App
-Console
-Events
-Exceptions
-...
-Libraries(Folder Containing Individual PHP files of classes from original file)
-Providers
-helpers.php(File containing all functions from original file)
-User.php
-bootstrap
-...
-...

Laravel use custom function into project in Laravel 4

i have some custom function and i'm trying to use that into project, for example:
function makeText($str1, $str2){
return $str1 . ' '. $str2;
}
and i want to use this function in view such as :
<div style='float:left;'>MakeText : {{makeText("Hello","World");}}</div>
makeText is only sample function, witch folder must be put functions method such as UF.php containes all functions and how to define this file to laravel and use it?
You could follow Laravel’s conventions and create a helpers.php file in your app directory. Be sure to auto-load it with Composer though:
"autoload": {
"classmap": [
//
],
"files": [
"app/helpers.php"
]
},
You can then use the function any where in your application, including views.
Laravel gives you a few options. You can include your function definition inside of any of the files that get automatically included and achieve the result you want, such as /app/start/global.php, /bootstrap/start.php, /app/routes.php or many others. The problem with this approach is that, depending on the name of your function, there is a non-negligible likelihood that the name might conflict with one that is already taken (or may get taken later). Also, if you ever need to debug this function you will need to be able to find it later.
You can get around this issue by placing your function inside of a class, and then call that class a service. You can then inject that class into your controller via dependency injection and then pass that data to your view:
class MyService
{
public function makeText($param1, $param2)
{
return $param1 . ' ' . $param2;
}
}
class AController extends BaseController
{
public function __construct(MyService $serv)
{
$this->serv = $serv;
}
public function aRoute()
{
return View::make('some.view')
->with('serv', $this->serv);
}
}
And then in your view:
<div style='float:left;'>MakeText : {{ $serv->makeText("Hello","World"); }}</div>
This will help you prevent naming collisions because you can easily place MyService into any namespace that makes sense. It will also help you keep your code organized better.
Something this simple will probably not require a service provider, but as you add complexity to your project it would be an easy step to do once you need to.

Categories