Skip to content Skip to sidebar Skip to footer

Important Function in Laravel

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!

  1. 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'; }
  2. blank() The blank function checks if a value is empty. This is useful for the opposite case of filled().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 }
  3. 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
  4. 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'
  5. 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
  6. 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
  7. 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
  8. logger() The logger function logs a message to the log file.phplogger('This is a debug message.');
  9. cookie() The cookie function creates a new cookie instance.php$cookie = cookie('name', 'value', 60); return response('Hello')->cookie($cookie);
  10. 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>
  11. csrf_token() The csrf_token function retrieves the current CSRF token.php$token = csrf_token(); echo $token; // Outputs the current CSRF token
  12. encrypt() and decrypt() The encrypt function encrypts a given value. The decrypt function decrypts a given value.phpC$encryptedValue = encrypt('mySecret'); $decryptedValue = decrypt($encryptedValue); echo $decryptedValue; // Outputs: mySecret
  13. e() The e function escapes HTML entities in a string.php$userInput = '<script>alert("Hello")</script>'; echo e($userInput); // Outputs: &lt;script&gt;alert(&quot;Hello&quot;)&lt;/script&gt;
  14. 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
  15. broadcast() The broadcast function broadcasts an event.php broadcast(new UserRegistered($user));
  16. bcrypt() The bcrypt function hashes a value using Bcrypt.php$hashedPassword = bcrypt('password'); echo $hashedPassword; // Outputs a hashed password string
  17. 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]]
  18. 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
  19. 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]]
  20. report() The report function reports an exception.phptry { // Some code that may throw an exception } catch (Exception $e) { report($e); }
  21. resolve() The resolve function resolves a service from the Laravel service container.php$service = resolve('App\Services\MyService'); $service->performTask();
  22. session() The session function gets or sets session values.phpsession(['key' => 'value']); $value = session('key'); echo $value; // Outputs: value
  23. 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'; }
  24. 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
  25. 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'; }
  26. 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>
  27. trans() The trans function translates the given message.phpecho trans('messages.welcome'); // Outputs: 'Welcome' or a translated message
  28. 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
  29. 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
  30. str_plural() The str_plural function returns the plural form of a given word.php$plural = str_plural('car'); echo $plural; // Outputs: cars
  31. str_singular() The str_singular function returns the singular form of a given word.php$singular = str_singular('cars'); echo $singular; // Outputs: car
  32. camel_case() The camel_case function converts a string to camel case.php$camel = camel_case('hello_world'); echo $camel; // Outputs: helloWorld
  33. kebab_case() The kebab_case function converts a string to kebab case.php$kebab = kebab_case('helloWorld'); echo $kebab; // Outputs: hello-world
  34. snake_case() The snake_case function converts a string to snake case.php$snake = snake_case('helloWorld'); echo $snake; // Outputs: hello_world
  35. title_case() The title_case function converts a string to title case.php$title = title_case('hello world'); echo $title; // Outputs: Hello World
  36. 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
  37. 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
  38. 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
  39. 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!

Leave a comment