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
Using Laravel: Streamlining Web Development with PHPUsing Laravel: Streamlining Web Development with PHPApr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel: An Introduction to the PHP Web FrameworkLaravel: An Introduction to the PHP Web FrameworkApr 19, 2025 am 12:15 AM

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel: MVC Architecture and Best PracticesLaravel: MVC Architecture and Best PracticesApr 19, 2025 am 12:13 AM

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel: Key Features and Advantages ExplainedLaravel: Key Features and Advantages ExplainedApr 19, 2025 am 12:12 AM

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Building Backend with Laravel: A GuideBuilding Backend with Laravel: A GuideApr 19, 2025 am 12:02 AM

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft