Laravel organize helper functions - php

Please, don't talk to technical in the answers:-D I am not a hardcore programmer.
What is a good way to store certain functions in Laravel? I have functions that apply on a "post" only or "media" only, like getAttributeList or getComponents. I say "Post" and "Media" because both have their own controller, model and views. It feels wrong to put it in the model because that should be database stuff right? And traits are more for recurring functions all over the place, right? So, right now I have one big file called Helpers.php. And uh, it is getting large... should I simply separate it in PostHelpers.php, MediaHelpers.php etc? Or is there a more elegant way in Laravel to do it?

It is quite simple : Just check your composer.json file at root directory of ur app. and under autoload section add :
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": ["app/helper.php"],
"classmap": [
"database/seeds",
"database/factories"
]
"files": ["app/helper.php"], This is the line you need to add in ur composer file and provide the path to file .
In my case i have created a file helper.php in App directory where i keep all my functions .
after this run this command :
composer dump-autoload
Now u can access your functions anywhere.

In your composer json file check this snippet
"autoload": {
"files": [
"app/Helpers/global_helper.php"
],
As you see I have auto loaded 1 single file called global_helper.php in a folder called Helpers Now in this file I have a function called loadHelper(...$files)
What this function does is
if (!function_exists('loadHelper')) {
function loadHelper(...$file_names)
{
foreach ($file_names as $file) {
include_once __DIR__ . '/' . $file . '_helper.php';
}
}
}
You can pass your file name as array or string and it will include those files into your Controller constructor
So In my Controller whenever I want some helper function I create a saperate helper file for that controller then in constructor i ust include it.
I am not sure if there is any better solution but so far this is how I am making all my projects .
I hope this will help you ;)

Related

Not getting session data in custom helper file - Laravel 5.8

Actually, I am trying to define a constant and setting value from the session
in a custom helper added using Helper Service Provider. But not getting the session data in here.
I have added a Helper using Helper Service Provider, It's working fine.
But trying to get the session value.
In HelperServiceProvider.php
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
require_once($filename);
}
}
And in ERPHelper.php in App/Helpers folder, I am trying to get the session data. But not getting the session value.
$company = session('company');
This is often down to the middleware. If you're setting the company session value under the web middleware, you might not be able to retrieve this is in a helper function registered by the service provider.
Also, out of interest, why are you setting this in a constant? It seems odd to me to use a the session helper to retrieve a value and then set it in a constant. A constant should probably not be used in this way but also you are adding an additional layer of abstraction. Why not just call session('company') as and when you need it?
I load in a helper Bootstrap.php via the composer.json file in the autoload section:
"autoload": {
"files": [
"app/Helpers/Bootstrap.php"
],
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database"
]
},
Then in the Bootstrap.php you could run your glob to load the relevant files.
That said, this still might not help because you're outside the web middleware. Can you not pass the session value to your helper function?
// Helper function.
function myErpHelper($companySessionValue) {
// My code here...
}
// Calling the helper function.
myErpHelper(session('company'));

Laravel Route Group for Views

I have below configuration in my Laravel /routes/web.php:
Route::group(['prefix' => 'admin'], function(){
Route::get('/', function() {
return view('admin.login');
});
});
If you observe, I have mentioned view('admin.login') this calls /resources/views/admin/login.blade.php. Which holds good as of now.
But for this Route group, I will have all my views inside /resources/views/admin. Thus, I do not want to use admin before every view-name.
Is there any possible parameter at Route::group level by which I can define namespace of my views, so that the Laravel searches my views in the particular directory inside /resources/views/?
I faced the same problem and created a helper function it worked ...
added a helpers directory under app directory app\Helpers\functions.php
function adminView($file){
return view('foo.' . $file);
}
in composer.json file registered this file
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
},
"files": ["app/Helpers/functions.php"]
},
just run composer dump-autoload and you can use this helper function
You can use
View::addNamespace('admin', '/path/to/admin/views'); or View::addLocation('/path/to/your/admin/views');
to specify your admin view folder in your route file.
with the first method you can use
return view('admin::view.name'); and with the second method you can use view name directly like return view('view.name');

How can I write an accessible class in the whole of project?

I use Laravel framework and this is my current directory:
As you see, there is a class named Log (the one I've selected). Now I need to make it global. I mean I want to make it accessible in everywhere and be able to I make a object (instance) of it in following files:
All files of classe folder
All controller
web.php file of
All file of views
Anyway I want to be able to make a instande of it and call its methods everywhere like this:
$obj = new Log();
$obj->insert($message);
How can I do that?
You can create global Laravel helper:
if (! function_exists('log')) {
function log($message)
{
(new Log)->insert($message);
}
}
Put it in helpers.php and add this to composer.json to load the helpers file:
"autoload": {
....
"files": [
"app/someFolder/helpers.php"
]
},
Then you'll be able to use this helper globally:
log('User added');
In views:
{{ log('User added') }}
Update
#stack, you're using wrong syntax for JSON (screenshot in comments), here's correct one:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/helpers.php"
]
},

Laravel5, where to put this generic code

I have some php lines which will be used very often in my application. So I would like to build a function and call it every where in my app. My function could be :
static function array_matiere($id_ecole) {
return $something;
}
I tried to put this code in a controller and then call it like that :
$liste_matieres = MatieresController::array_matieres(Session::get('id_ecole'));
It works, but where to put this kind of function ? in the controller ? in a method file ? what is the best practice ?
Thanks for your responses.
Dominique
There are multiple ways to implement this. look here
Method 1 This method is highly suggested by Laravel Expert ( JeffreyWay)
If your helper functions are similar to the way laravel 5 ones work, i.e Illuminate/Support/helpers.php you could just create a helpers.php and have composer do the autoloading for you.
Edit your composer.json file and add the file to the autoloading key. In my example my app is called Tasky so just add the files key and reference helpers.php.
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"Tasky\\": "app/"
},
"files": [
"app/Support/helpers.php"
]
},
That way you just create your file inside app/Support/helpers.php and all your common function based view helpers or other helpers can go here. If you take the class based approach then the above is great.
Also then remember to just run the following once.
$ composer dumpautoload
Source
Method 2
Please Follow the link and read answer & Its comments
Whenever u need to include a piece of code providing some functionality through out your application then the best way in Laravel is to make Service class inside app/Services and then you can use that class anywhere in your application using
use App\Services\YourServiceName;

Where can I put laravel 4 filter classes?

In laravel 4, you can create filter classes instead of putting the entire filter inside a closure -- great. But do these filters have to be entirely in the app/filters.php or app/routes.php?
Generally I like to do one file per class, but I imagine there's something better to do then a bunch of includes in the filters.php file. Where would you put these for laravel to find them automatically? For example:
Route::filter('Thing', 'ThingFilter');
# can I put this in its own file and have laravel automatically use it?
class ThingFilter {
function filter() { ... }
}
I've all my filters in a separate directory called filters.
And here's how my filters.php file look like...
//---------------------------------------------------------
// Route Filters
//---------------------------------------------------------
Route::filter('auth', 'AuthFilter#default');
Route::filter('auth.basic', 'AuthFilter#basic');
Route::filter('guest', 'AuthFilter#guest');
Route::filter('csrf', 'CsrfFilter');
I autoload them via composer.json
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/filters",
"app/presenters",
"app/repositories",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
After you update your composer.json file, you need to run the command
composer dump-autoload
To verfiy that you files will be loaded, check out
vendor/composer/autoload_classmap.php
There isn't a default to my knowledge, but you can call ClassLoader::addDirectories(array(app_path().'/filters')); to register your filter directory. The correct place to put that is in app/start/global.php where you should see some folders already being registered.
There is a 'local.php' which seems a candidate, but this is only meant for specific environments (usually development, provided you add a proper array or closure in $app->detectEnvironment()).

Categories