Skip to content

Helpers

Giới thiệu (Introduction)

Laravel bao gồm nhiều hàm PHP "helper" toàn cục. Nhiều trong số này được framework sử dụng nội bộ, nhưng bạn hoàn toàn tự do dùng trong ứng dụng của mình.

Arrays & Objects

Arr::accessible()

Kiểm tra giá trị có "accessible" (array hoặc ArrayAccess):

php
use Illuminate\Support\Arr;

Arr::accessible(['a' => 1]); // true
Arr::accessible('abc');       // false

Arr::add()

Thêm key/value nếu chưa tồn tại:

php
$array = Arr::add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]

Arr::collapse()

Gộp mảng nhiều chiều thành một mảng:

php
$array = Arr::collapse([[1, 2], [3, 4], [5]]);
// [1, 2, 3, 4, 5]

Arr::dot()

Flatten mảng dùng dot notation:

php
$array = Arr::dot(['products' => ['desk' => ['price' => 100]]]);
// ['products.desk.price' => 100]

Arr::except()

Loại bỏ keys:

php
$array = Arr::except(['a' => 1, 'b' => 2, 'c' => 3], ['b']);
// ['a' => 1, 'c' => 3]

Arr::first() / Arr::last()

php
$first = Arr::first([100, 200, 300], fn ($v) => $v >= 150);
// 200

Arr::flatten()

php
$array = Arr::flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);
// ['Joe', 'PHP', 'Ruby']

Arr::get() / Arr::set()

Dùng dot notation:

php
$value = Arr::get($array, 'products.desk.price');
Arr::set($array, 'products.desk.price', 200);

Arr::has() / Arr::hasAny()

php
Arr::has($array, 'products.desk');      // true
Arr::hasAny($array, ['key1', 'key2']); // true nếu có ít nhất 1

Arr::map()

php
$array = Arr::map([1, 2, 3], fn ($v) => $v * 2);
// [2, 4, 6]

Arr::only()

php
$array = Arr::only(['a' => 1, 'b' => 2, 'c' => 3], ['a', 'c']);
// ['a' => 1, 'c' => 3]

Arr::pluck()

php
$names = Arr::pluck($users, 'name');

Arr::sort() / Arr::sortBy()

php
$sorted = Arr::sort([3, 1, 2]);
// [1, 2, 3]

Arr::where() / Arr::whereNotNull()

php
$result = Arr::where([100, 200, 300], fn ($v) => $v > 150);
// [200, 300]

data_get() / data_set()

Truy xuất nested data dùng dot notation và wildcards:

php
$data = ['products' => ['desk' => ['price' => 100]]];
data_get($data, 'products.desk.price'); // 100

head() / last()

php
$first = head([1, 2, 3]); // 1
$last = last([1, 2, 3]);  // 3

Numbers

php
use Illuminate\Support\Number;

Number::abbreviate(1000);        // '1K'
Number::format(100000);          // '100,000'
Number::percentage(10);          // '10%'
Number::currency(1000, 'USD');   // '$1,000.00'
Number::fileSize(1024);          // '1 KB'
Number::forHumans(1000);         // '1 thousand'
Number::ordinal(1);              // '1st'
Number::spell(5);                // 'five'
Number::pairs(25, 10);           // [[1, 10], [11, 20], [21, 25]]

Paths

php
app_path();                    // app/
app_path('Http/Controllers');
base_path();                   // project root
config_path();                 // config/
database_path();               // database/
lang_path();                   // lang/
public_path();                 // public/
resource_path();               // resources/
storage_path();                // storage/
storage_path('app/file.txt');

URLs

php
action([UserController::class, 'index']);
asset('img/photo.jpg');
route('route.name');
secure_asset('img/photo.jpg');
secure_url('user/profile');
to_route('users.show', ['user' => 1]);
url('/user/profile');
url()->current();
url()->full();
url()->previous();

Miscellaneous (Khác)

abort() / abort_if() / abort_unless()

php
abort(403);
abort_if(!$user->isAdmin(), 403);
abort_unless($user->isAdmin(), 403);

auth() / back() / bcrypt()

php
$user = auth()->user();
return back()->withInput();
$hash = bcrypt('my-secret-password');
php
$collection = collect([1, 2, 3]);
$value = config('app.name');
$cookie = cookie('name', 'value', $minutes);

dd() / dump() / env()

php
dd($value);        // Dump and die
dump($value);      // Dump and continue
env('APP_DEBUG');
env('APP_DEBUG', false); // với default

event() / info() / logger()

php
event(new UserRegistered($user));
info('Thông tin hữu ích');
logger('Debug message');
logger()->error('Lỗi nghiêm trọng');

now() / today() / old()

php
$now = now();       // Carbon instance
$today = today();   // Carbon (start of day)
$value = old('name');

redirect() / report() / request() / response()

php
return redirect('/home');
report($exception);
$value = request('key');
return response('Hello', 200);
return response()->json(['key' => 'value']);

session() / validator() / view()

php
$value = session('key');
session(['key' => 'value']);
$v = validator($data, $rules);
return view('welcome', ['name' => 'Taylor']);

Các tiện ích khác (Other Utilities)

Benchmarking

php
use Illuminate\Support\Benchmark;

Benchmark::measure(fn () => User::find(1)); // "0.1 ms"

Dates & Time

php
$now = now();
$date = now()->plus(hours: 2, minutes: 30);

Deferred Functions

Chạy function sau khi response được gửi:

php
use function Illuminate\Support\defer;

defer(fn () => Metrics::report());

Pipeline

php
use Illuminate\Support\Facades\Pipeline;

$result = Pipeline::send($content)
    ->through([
        RemoveBadWords::class,
        FilterPhoneNumbers::class,
    ])
    ->thenReturn();

Sleep

Testable wrapper cho sleep():

php
use Illuminate\Support\Sleep;

Sleep::for(2)->seconds();
Sleep::until(now()->addMinute());