CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

01 April, 2024

Creating Your Own PHP Helpers in a Laravel Project

 Programing Coderfunda     April 01, 2024     No comments   

---



Laravel provides many excellent helper functions that are convenient for doing things like working with arrays, file paths, strings, and routes, among other things like the beloved dd() function.


You can also define your own set of helper functions for your Laravel applications and PHP packages, by using Composer to import them automatically.


If you are new to Laravel or PHP, let’s walk through how you might go about creating your own helper functions that automatically get loaded by Laravel.


Creating a Helpers file in a Laravel App




The first scenario you might want to include your helper functions is within the context of a Laravel application. Depending on your preference, you can organize the location of your helper file(s) however you want, however, here are a few suggested locations:




*
app/helpers.php


*
app/Http/helpers.php






I prefer to keep mine in app/helpers.php in the root of the application namespace.


Autoloading




To use your PHP helper functions, you need to load them into your program at runtime. In the early days of my career, it wasn’t uncommon to see this kind of code at the top of a file:
require_once ROOT . '/helpers.php';




PHP functions cannot be autoloaded. However, we have a much better solution through Composer than using require or require_once.


If you create a new Laravel project, you will see an autoload and autoload-dev keys in the composer.json file:
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},




If you want to add a helpers file, composer has a files key (which is an array of file paths) that you can define inside of autoload:
"autoload": {
"files": [
"app/helpers.php"
],
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},




Once you add a new path to the files array, you need to dump the autoloader:
composer dump-autoload



Now on every request the helpers.php file will be loaded automatically because Laravel requires Composer’s autoloader in public/index.php:
require __DIR__.'/../vendor/autoload.php';



Defining Functions




Defining functions in your helpers class is the easy part, although, there are a few caveats. All of the Laravel helper files are wrapped in a check to avoid function definition collisions:
if (! function_exists('env')) {
function env($key, $default = null) {
// ...
}
}




This can get tricky, because you can run into situations where you are using a function definition that you did not expect based on which one was defined first.


I prefer to use function_exists checks in my application helpers, but if you are defining helpers within the context of your application, you could forgo the function_exists check.


By skipping the check, you’d see collisions any time your helpers are redefining functions, which could be useful.


In practice, collisions don’t tend to happen as often as you’d think, and you should make sure you’re defining function names that aren’t overly generic. You can also prefix your function names to make them less likely to collide with other dependencies.


Helper Example




I like the Rails path and URL helpers that you get for free when defining a resourceful route. For example, a photos resource route would expose route helpers like new_photo_path, edit_photo_path`, etc.


When I use resource routing in Laravel, I like to add a few helper functions that make defining routes in my templates easier. In my implementation, I like to have a URL helper function that I can pass an Eloquent model and get a resource route back using conventions that I define, such as:
create_route($model);
edit_route($model);
show_route($model);
destroy_route($model);



Here’s how you might define a show_route in your app/helpers.php file (the others would look similar):
if (! function_exists('show_route')) {
function show_route($model, $resource = null)
{
$resource = $resource ?? plural_from_model($model);

return route("{$resource}.show", $model);
}
}

if (! function_exists('plural_from_model')) {
function plural_from_model($model)
{
$plural = Str::plural(class_basename($model));

return Str::kebab($plural);
}
}




The plural_from_model() function is just some reusable code that the helper route functions use to predict the route resource name based on a naming convention that I prefer, which is a kebab-case plural of a model.


For example, here’s an example of the resource name derived from the model:
$model = new App\LineItem;
plural_from_model($model);
// => line-items

plural_from_model(new App\User);
// => users




Using this convention you’d define the resource route like so in routes/web.php:
Route::resource('line-items', 'LineItemsController');
Route::resource('users', 'UsersController');



And then in your blade templates, you could do the following:

{{ $lineItem->name }}




Which would produce something like the following HTML:

Line Item #1




Packages




Your Composer packages can also use a helpers file for any helper functions you want to make available to projects consuming your package.


You will take the same approach in the package’s composer.json file, defining a files key with an array of your helper files.


It’s imperative that you add function_exists() checks around your helper functions so that projects using your code don’t break due to naming collisions.


You should choose proper function names that are unique to your package, and consider using a short prefix if you are afraid your function name is too generic.


Learn More




Check out Composer’s autoloading documentation to learn more about including files, and general information about autoloading classes.



The post Creating Your Own PHP Helpers in a Laravel Project appeared first on Laravel News.


Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Write Single Page Applications using Laravel Splade--- Laravel Splade, created by by Pascal Baljet, is a super easy way to build single-page applications (SPA) using Laravel Blade templates. Splade… Read More
  • Copy and fill column from datagridview to another VBNETI want to copy and divide data from the "range" column in dgv1 to dgv2, I have tried this code but it still doesn't work as I want. Any suggestions?… Read More
  • Weekly /r/Laravel Help ThreadAsk your Laravel help questions here. To improve your chances of getting an answer from the community, here are some tips: * What steps have you ta… Read More
  • Laravel 9 Upgrade: Write Operations Now Overwrite Existing FilesPer the v9 upgrade guide, "write operations such as put, write, and writeStream now overwrite existing files by default." I'm not exactly sure what … Read More
  • Inertia and React or VueHi just checking your thoughts on whether to learn React or Vue, I want to learn React as it may be better to find work and it has a larger ecosystem … Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Enabling authentication in swagger
    I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. S...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Locale-aware Number Parsing in Laravel 12.15 - 5/21/2025
  • Handle Fluent Values as Arrays with Laravel's array() Method - 5/18/2025
  • Chargebee Starter Kit for Billing in Laravel - 5/20/2025
  • Streamline Pipeline Cleanup with Laravel's finally Method - 5/18/2025
  • Validate Controller Requests with the Laravel Data Package - 5/19/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda