Home > PHP Framework > Laravel > body text

Sharing my seven favorite Laravel helper functions

藏色散人
Release: 2020-08-12 13:40:48
forward
2768 people have browsed it

The following is the Sharing my seven favorite Laravel helper functions framework tutorial column to introduce and share my seven favorite Sharing my seven favorite Laravel helper functions auxiliary functions. I hope it will be helpful to friends in need!

Sharing my seven favorite Laravel helper functions

As a PHP full-stack developer mainly based on Sharing my seven favorite Laravel helper functions, I will often look for some frameworks that can be used by me to effectively reduce development time or reduce code. complexity approach.

The following are some good auxiliary methods that I have compiled that I often use in daily life. Most of the methods in this article are based on Sharing my seven favorite Laravel helper functions7 and earlier versions. (If you encounter problems, please first check whether it is a version compatibility issue)

Let’s find out

Str::limit()

Our first helper function takes a string and truncates it with a set character length limit . It takes two required parameters: the string you want to truncate, and the character length limit for the returned truncated string.

use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);

// The quick brown fox ...
Copy after login

You can also pass in the third optional parameter to control what is displayed after the returned string.

use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, '[...]');

// The quick brown fox [...]
Copy after login

I find this perfect for shortening a large block of text into a summary or post preview for a list of articles.

head()

This function is awesome. A simple method usually consists of several nested primitive PHP functions, head() will return the first element of the array. I've used it in many different applications due to its global and ubiquitous nature.

$array = [100, 200, 300];

$first = head($array);

// 100
Copy after login

Want to do it the other way around? Use the last method to get the last element of the array.

$array = [100, 200, 300];

$last = last($array);

// 300
Copy after login

This is the best approach regarding using head and last methods as they don't affect the original array at all.

Str::between()

As the name suggests, Str::between() will return the content in the string. If the specified string is not found, null is returned.

use Illuminate\Support\Str;

$slice = Str::between('My name is Inigo Montoya.', 'My name is ', '.');

// 'Inigo Montoya'
Copy after login

I like to use this method to get information from () or [], return specific parts of the url, or even parse from html tags data.

blank()

It is similar to empty(), but better to use . It returns a Boolean value based on whether the parameter you pass in contains actual data.

// all of these return true
blank('');
blank('   ');
blank(null);
blank(collect());

// all of these return false
blank(true);
blank(false);
blank(0);
Copy after login

This helper function is particularly useful when combined with form validation to remove data that is not entered in the API specification.
It is better to use than empty(trim()).

Str::contains()

Our long-awaited auxiliary function, determines whether a string contains another string. This question has been asked many times on StackOverflow and other programming forums, because currently in normal PHP programs only strpos.

use Illuminate\Support\Str;

$contains = Str::contains('My name is Inigo Montoya.', 'Inigo');

// true

$contains = Str::contains('My name is Inigo Montoya.', 'Andrew');

// false
Copy after login

With the recent RFC approval, PHP will soon have its own str_contains method which will make this method obsolete. But until then, it is one of the most useful helper functions in Sharing my seven favorite Laravel helper functions.

Arr::pluck()

This method is arguably one of the more powerful methods I listed in this article, Arr::pluck Iterate over a multidimensional array and retrieve all values ​​ for a given key.

Let's look at a simple example:

use Illuminate\Support\Arr;

$array = [
    ['website' => ['id' => 1, 'url' => 'reddit.com']],
    ['website' => ['id' => 2, 'url' => 'twitter.com']],
    ['website' => ['id' => 3, 'url' => 'dev.to']],
];

$names = Arr::pluck($array, 'website.url');

// ['reddit.com', 'twitter.com', 'dev.to']
Copy after login

Pass in an array and a dot notation string to determine the key value we want, then iterate through the multi-dimensional array and assign the specified key A one-dimensional array of corresponding values ​​is returned to us.

I've used this method many times on the returned API data (when I felt I didn't need to use the entire collection). It makes it very easy to get an array of IDs, names, or other properties without creating an entire foreach loop.

collect()

Once I find information about collections, I never stop using them. This is probably the helper function I find myself using the most, it lets you convert an array into a collection.

Why is this important? Because collections come with a large number of convenience methods, you can combine them to perform various filtering, sorting, and modification operations on the array with the simplest closure parameters. No foreach loops, no intermediate variables, just clean code.

Look at this simple example:

$collection = collect(['Keys', 'Krates']);

return $collection->map(function ($value) {
    return Str::upper($value);
});

// ['KEYS', 'KRATES']

return $collection->filter(function ($value) {
    return strlen($value) > 4;
});

// ['Krates']
Copy after login

Honestly, this is just the tip of the collection iceberg. I use them both in my projects, especially when I'm dealing with large and complex data sets that don't come from a database model. CSV data, external API requests and directory structures are all available from drop collections.

This is what I know now!

Original address: https://dev.to/aschmelyun/my-favorite-la...

Translation address: https://learnku.com/laravel/t/43776

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

Related labels:
source:learnku.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template