September 30, 2024 · 4 min read · 78 views
We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.
Helpers in Laravel are convenient PHP functions that simplify common tasks and enhance the efficiency of your code. These functions are globally available and can be used anywhere in your application. Laravel provides a wide array of built-in helper functions, and you can also create custom helpers to suit your specific needs.
Helpers streamline your code by providing straightforward solutions for common tasks, such as string manipulation, array handling, URL generation, and more. They enhance code readability and maintainability, enabling developers to write cleaner and more efficient code.
Laravel comes with numerous built-in helper functions categorized into various groups.
String helpers simplify string manipulation. Here are some of them:
Str::after($subject, $search)
- Returns the portion of the string after the given value.
Str::before($subject, $search)
- Returns the portion of the string before the given value.
Str::contains($haystack, $needles)
- Checks if a string contains a given substring.
Str::kebab($string)
- Transform a string into a kebab case.
<?php
use Illuminate\Support\Str;
Str::after('This is a test', 'This is'); // Output: ' a test'
Str::before('This is my name', 'my name'); // Output: 'This is '
Str::contains('Laravel is great', 'great'); // Output: true
Str::kebab('fooBar'); // Output: 'foo-bar'
Array helpers assist in array manipulation. Some of the most useful array helpers include:
Arr::add($array, $key, $value)
- Adds a key/value pair to an array if the key doesn't exist.
Arr::except($array, $keys)
- Removes the specified key/value pairs from an array.
Arr::only($array, $keys)
- Returns only the specified key/value pairs from an array.
<?php
use Illuminate\Support\Arr;
$array = ['name' => 'John', 'age' => 30, 'city' => 'New York'];
$array = Arr::add($array, 'country', 'USA');
// Output: ['name' => 'John', 'age' => 30, 'city' => 'New York', 'country' => 'USA']
$array = Arr::except($array, ['age']);
// Output: ['name' => 'John', 'city' => 'New York', 'country' => 'USA']
$array = Arr::only($array, ['name', 'country']);
// Output: ['name' => 'John', 'country' => 'USA']
Path helpers provide convenient functions for working with file paths. Some of the most useful path helpers include:
app_path($path = '')
- Returns the fully qualified path to the app directory.
base_path($path = '')
- Returns the fully qualified path to the root of the application.
storage_path($path = '')
- Returns the fully qualified path to the storage directory.
<?php
app_path('Http/Controllers'); // Output: '/path/to/your/app/Http/Controllers'
storage_path('logs'); // Output: '/path/to/your/app/storage/logs'
URL helpers simplify URL generation and manipulation. Some of the most useful URL helpers include:
url($path)
- Generates a fully qualified URL to the given path.
route($name, $parameters = [])
- Generates a URL to a named route.
asset($path)
- Generates a URL for an asset using the current scheme of the request (HTTP or HTTPS).
<?php
url('/profile'); // Output: 'http://blog.com/profile'
route('profile.show', ['id' => 1]); // Output: 'http://blog.com/profile/1'
asset('images/logo.png'); // Output: 'http://blog.com/images/logo.png'
In addition to built-in helpers, you can create custom helper functions tailored to your application's needs. Let's create custom helpers for our blog post example to format the dates into a human-readable way.
Create a new PHP file in the app directory or a subdirectory of your choice. For example, app/Helpers/helpers.php
.
Add your custom helper functions in the newly created file. Here's an example of a custom helper function to format a date in a human-readable way:
<?php
if (!function_exists('format_date')) {
function format_date($date, $format = 'F j, Y') {
return \Carbon\Carbon::parse($date)->format($format);
}
}
To make the custom helpers globally available, you need to autoload the helpers file. Open the composer.json
file and add the path to the helpers file in the autoload section:
<?php
"autoload": {
"files": [
"app/Helpers/helpers.php"
],
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
After updating composer.json, run composer dump-autoload
to regenerate the autoload files.
Now you can use your custom helper functions anywhere in your application:
format_date('2023-10-15'); // Outputs: October 15, 2023
Helper functions in Laravel are powerful tools that simplify common tasks and enhance code readability. You can write more efficient and maintainable code by using built-in helpers and creating custom ones when needed. Whether manipulating strings, handling arrays, generating URLs, or working with file paths, Laravel's helpers provide a convenient and elegant solution.
Laravel 11 for Beginners: Using Custom and Built-in Commands
Laravel 11 for Beginners: Using Policies for Authorization
Laravel 11 for Beginners: Roles and Permissions with Spatie package
This article is part of our series Laravel 11 for Beginners: A Step-by-Step Guide to Learn the Concepts.
If you need help with a Laravel project let's get in touch.
Lucky Media is proud to be recognized as a Top Laravel Development Agency
Technologies:
Related Posts
Stay up to date
Be updated with all news, products and tips we share!