Table of Contents
array_dot()
array_get()
public_path()
Str::orderedUuid()
str_plural()
route()
#tap()
dump()
str_slug()
optional()
Home PHP Framework Laravel Ten recommended Laravel helper functions

Ten recommended Laravel helper functions

Jun 27, 2019 pm 06:05 PM
laravel

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
Copy after login

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
Copy after login
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
Copy after login

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');
Copy after login

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
Copy after login

str_plural()

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

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);
Copy after login

#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'
]);
Copy after login

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);
Copy after login

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
Copy after login

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;
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 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.

See all articles