Home  >  Article  >  PHP Framework  >  [Organize and share] Several practical Laravel auxiliary functions

[Organize and share] Several practical Laravel auxiliary functions

青灯夜游
青灯夜游forward
2022-12-28 21:01:061646browse

As a PHP full-stack developer who mainly uses Laravel, I often look for methods in some frameworks that can be used by me to effectively reduce development time or reduce code complexity. Below are some good auxiliary methods that I have compiled that I often use in daily life. Let’s find out ✨

[Organize and share] Several practical Laravel auxiliary functions

The methods in this article are mostly based on Laravel7 and earlier versions. (If you encounter problems, please check whether it is a version compatibility issue first)

Str::limit()

Our first auxiliary function Get a string and truncate 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. [Related recommendations: laravel video tutorial]

use Illuminate\Support\Str;

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

// The quick brown fox ...

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 [...]

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

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

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'

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);

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 ordinary PHP programs you can only use 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

With With 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 Laravel.

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']

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 allows you to convert an array into a collection.

Why is this important? Because collections come with a large number of convenience methods, you can combine them together 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']

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-laravel-helpers-and-how-to-use-them-28ij

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

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of [Organize and share] Several practical Laravel auxiliary functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete