While Laravel’s well-known helper functions are widely used, many lesser-known ones can significantly enhance your development workflow. These helper functions come in handy and can be called in any part of your Laravel codebase. They streamline tasks, improve code readability, and boost productivity. Here are 40 rare yet valuable Laravel helper functions:
Let’s Start with the Basics and Move to the Best
You will discover many beautiful functions that will boost your application’s speed and efficiency. Let’s go!
- filled() The
filled
function checks if a value is not empty, which can be more intuitive than using!empty()
.php$value = 'some text'; if (filled($value)) { echo 'Value is not empty'; // This will be output } else { echo 'Value is empty'; }
- blank() The
blank
function checks if a value is empty. This is useful for the opposite case offilled()
.php$value1 = ''; $value2 = null; $value3 = 'Laravel'; if (blank($value1)) { echo 'Value 1 is blank'; // Outputs this } if (blank($value2)) { echo 'Value 2 is blank'; // Outputs this } if (blank($value3)) { echo 'Value 3 is blank'; // Does not output this }
- retry() The
retry
function retries an operation a given number of times with a specified delay between attempts. This is useful for operations that might fail intermittently, such as network requests or database transactions.php$result = retry(5, function () { // Simulate a risky operation that might fail if (rand(0, 1)) { throw new Exception('Failed'); } return 'Success'; }, 100); echo $result; // Outputs: 'Success' if the operation eventually succeeds
- throw_if() The
throw_if
function throws an exception if a given condition is true. This can make your code cleaner by reducing nested if statements.php$user = null; throw_if(!$user, Exception::class, 'User not found'); // This will throw an exception with the message 'User not found'
- transform() The
transform
function conditionally transforms a value using a given callback.php$input = 'hello world'; $output = transform($input, function ($value) { return strtoupper($value); }, 'default value'); echo $output; // Outputs: HELLO WORLD
- optional() The
optional
function allows you to access properties or call methods on an object that may be null without triggering an error.php$user = null; $name = optional($user)->name; echo $name; // Outputs: nothing (null) without causing an error
- cache() The
cache
function retrieves or stores items in the cache.php$value = cache('key', function () { return DB::table('users')->get(); }, 60); echo $value; // Outputs cached user data
- logger() The
logger
function logs a message to the log file.phplogger('This is a debug message.');
- cookie() The
cookie
function creates a new cookie instance.php$cookie = cookie('name', 'value', 60); return response('Hello')->cookie($cookie);
- csrf_field() The
csrf_field
function generates a hidden input field containing the CSRF token.html<form method="POST" action="/submit"> {{ csrf_field() }} <input type="text" name="name"> <button type="submit">Submit</button> </form>
- csrf_token() The
csrf_token
function retrieves the current CSRF token.php$token = csrf_token(); echo $token; // Outputs the current CSRF token
- encrypt() and decrypt() The
encrypt
function encrypts a given value. Thedecrypt
function decrypts a given value.phpC$encryptedValue = encrypt('mySecret'); $decryptedValue = decrypt($encryptedValue); echo $decryptedValue; // Outputs: mySecret
- e() The
e
function escapes HTML entities in a string.php$userInput = '<script>alert("Hello")</script>'; echo e($userInput); // Outputs: <script>alert("Hello")</script>
- rescue() The
rescue
function executes a callback and returns a default value if an exception occurs.php$value = rescue(function () { return riskyOperation(); }, 'default'); echo $value; // Outputs: 'default' if an exception occurs
- broadcast() The
broadcast
function broadcasts an event.phpbroadcast(new UserRegistered($user));
- bcrypt() The
bcrypt
function hashes a value using Bcrypt.php$hashedPassword = bcrypt('password'); echo $hashedPassword; // Outputs a hashed password string
- data_fill() The
data_fill
function fills in missing data in an array or object using “dot” notation.php$data = ['product' => ['name' => 'Desk']]; data_fill($data, 'product.price', 100); print_r($data); // Outputs: ['product' => ['name' => 'Desk', 'price' => 100]]
- data_get() The
data_get
function retrieves a value from a nested array or object using “dot” notation.php$data = ['product' => ['name' => 'Desk', 'price' => 100]]; $name = data_get($data, 'product.name'); echo $name; // Outputs: Desk
- data_set() The
data_set
function sets a value within a deeply nested array or object using “dot” notation.php$data = ['product' => ['name' => 'Desk']]; data_set($data, 'product.price', 200); print_r($data); // Outputs: ['product' => ['name' => 'Desk', 'price' => 200]]
- report() The
report
function reports an exception.phptry { // Some code that may throw an exception } catch (Exception $e) { report($e); }
- resolve() The
resolve
function resolves a service from the Laravel service container.php$service = resolve('App\Services\MyService'); $service->performTask();
- session() The
session
function gets or sets session values.phpsession(['key' => 'value']); $value = session('key'); echo $value; // Outputs: value
- validator() The
validator
function creates a new validator instance.php$validator = validator(['name' => 'John'], ['name' => 'required|string|max:255']); if ($validator->fails()) { echo 'Validation failed'; } else { echo 'Validation succeeded'; }
- value() The
value
function returns the value it is given. If a Closure is given, it will be executed, and its result returned.php$value = value(function () { return 'result'; }); echo $value; // Outputs: result
- windows_os() The
windows_os
function checks if the application is running on Windows.phpif (windows_os()) { echo 'Running on Windows'; } else { echo 'Not running on Windows'; }
- method_field() The
method_field
function generates a hidden input field containing the spoofed HTTP verb.html<form method="POST" action="/update"> {{ method_field('PUT') }} {{ csrf_field() }} <input type="text" name="name"> <button type="submit">Update</button> </form>
- trans() The
trans
function translates the given message.phpecho trans('messages.welcome'); // Outputs: 'Welcome' or a translated message
- trans_choice() The
trans_choice
function translates the given message based on a count.phpecho trans_choice('messages.apples', 10); // Outputs: '10 apples' or a translated message
- str_slug() The
str_slug
function generates a URL-friendly “slug” from a given string.php$slug = str_slug('Laravel 8 Framework'); echo $slug; // Outputs: laravel-8-framework
- str_plural() The
str_plural
function returns the plural form of a given word.php$plural = str_plural('car'); echo $plural; // Outputs: cars
- str_singular() The
str_singular
function returns the singular form of a given word.php$singular = str_singular('cars'); echo $singular; // Outputs: car
- camel_case() The
camel_case
function converts a string to camel case.php$camel = camel_case('hello_world'); echo $camel; // Outputs: helloWorld
- kebab_case() The
kebab_case
function converts a string to kebab case.php$kebab = kebab_case('helloWorld'); echo $kebab; // Outputs: hello-world
- snake_case() The
snake_case
function converts a string to snake case.php$snake = snake_case('helloWorld'); echo $snake; // Outputs: hello_world
- title_case() The
title_case
function converts a string to title case.php$title = title_case('hello world'); echo $title; // Outputs: Hello World
- asset() The
asset
function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS).php$url = asset('images/logo.png'); echo $url; // Outputs: http://yourdomain.com/images/logo.png
- route() The
route
function generates a URL for a named route.php$url = route('user.profile', ['id' => 1]); echo $url; // Outputs: http://yourdomain.com/user/profile/1
- url() The
url
function generates a fully qualified URL to the given path.php$url = url('user/profile'); echo $url; // Outputs: http://yourdomain.com/user/profile
- mix() The
mix
function gets the path to a versioned Mix file.php$path = mix('js/app.js'); echo $path; // Outputs: /js/app.js?id=some-version-hash
By leveraging these lesser-known Laravel helper functions, you can simplify your code, enhance its readability, and improve overall productivity. Happy coding!