search
HomePHP FrameworkLaravelTen recommended Laravel helper functions

Ten recommended Laravel helper functions

array_dot()

function allows you to convert a multidimensional array into a one-dimensional array using dot notation.
$array = [
    'user' => ['username' => 'something'],
    'app' => ['creator' => ['name' => 'someone'], 'created' => 'today']
];
$dot_array = array_dot($array);
// [user.username] => something, [app.creator.name] => someone, [app.created] => today

array_get()

Function retrieves values ​​from a multidimensional array using dot notation.
$array = [
    'user' => ['username' => 'something'],
    'app' => ['creator' => ['name' => 'someone'], 'created' => 'today']
];
$name = array_get($array, 'app.creator.name');
// someone
The array_get() function also accepts an optional third parameter as a default value if key does not exist.
$name = array_get($array, 'app.created.name', 'anonymous');
// anonymous

public_path()

Returns the fully qualified absolute path to the public directory in your Laravel application. You can also pass the path to a file or directory in the public directory to get the absolute path to the resource. It will simply add public_path() to your parameters.
$public_path = public_path();
$path = public_path('js/app.js');

Str::orderedUuid()

(1) The function first generates a timestamp uuid. This uuid can be stored in an indexed database column. These uuids are created based on timestamps, so they keep your content indexed;
(2) When using this in Laravel 5.6, a Ramsey\Uuid\Exception\UnsatisfiedDependencyException is thrown. To resolve this issue, just run the following command to use the moontoast/math package
composer require laravel/passport=~7.0
use Illuminate\Support\Str;
return (string) Str::orderByUuid()
// A timestamp first uuid

str_plural()

Convert a string to plural form. This feature only supports English.
echo str_plural('bank');
// banks
echo str_plural('developer');
// developers

route()

Generate the route URL for the specified route.
$url = route('login');
// 如果路由接受参数,你可以简单地将它们作为第二个参数传递给一个数组。
$url = route('products', ['id' => 1]);
// 如果你想产生一个相对的 URL 而不是一个绝对的 URL,你可以传递 false 作为第三个参数。
$url = route('products', ['id' => 1], false);

#tap()

Accepts two parameters: a value and a closure. The value will be passed to the closure and the value will be returned. The closure return value doesn't matter.
$user = App\User::find(1);

return tap($user, function($user) {
    $user->update([
        'name' => 'Random'
    ]);
});
/**
  * 它不会返回布尔值,而是返回 User Model 。如果你没有传递闭包,你也可以使用 User Model 的任何方法。
  * 无论实际返回的方法如何,返回值都将始终为值。 在下面的例子中,它将返回 User Model 而不是布尔值。
  * update 方法返回布尔值,但由于用了 tap ,所以它将返回 User Model。
  */ 
$user = App\User::find(1);

return tap($user)->update([
    'name' => 'SomeName'
]);

dump()

will dump the given variables, and also supports passing in multiple variables at the same time. This is very useful for debugging.
$dump($var1);
dump($var1, $var2, $var3);

str_slug()

Generate a URL-friendly slug from the given string. You can use this feature to create a slug for your post or product title.
$slug = str_slug('Helpers in Laravel', '-');
// helpers-in-laravel

optional()

Accepts a parameter, you can call the parameter's method or access the property. If the passed object is null, methods and properties will return null instead of causing an error or throwing an exception.
$user = User::find(1);
return optional($user)->name;

For more Laravel related technical articles, please visit the Laravel Tutorial column to learn!

The above is the detailed content of Ten recommended Laravel helper functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version