Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Helpers: strings, arrays, dates

Besides its big features Laravel has hundreds of small functions for daily work: make an address from a title, truncate text, pull a value out of a nested array, show "3 hours ago". Knowing them saves writing the same things by hand.

Strings

use Illuminate\Support\Str;
 
Str::slug('How to Choose Tea');           // how-to-choose-tea
Str::limit('A very long headline', 11);   // A very long...
Str::title('war and peace');              // War And Peace
Str::random(16);                          // a random string
Str::uuid();                              // a unique identifier
Str::contains('laravel.com', '.com');     // true
Str::plural('post');                      // posts

Chains

The str() function returns an object whose methods can be called in a row:

$slug = str('  New Post: PHP 8.4  ')
    ->trim()
    ->lower()
    ->slug();
 
$initials = str('Anna Smith')->explode(' ')->map(fn ($word) => $word[0])->join('');

Arrays

use Illuminate\Support\Arr;
 
$user = ['name' => 'Anna', 'address' => ['city' => 'Paris']];
 
Arr::get($user, 'address.city');            // Paris
Arr::get($user, 'address.street', '—');     // —
Arr::only($user, ['name']);                 // ['name' => 'Anna']
Arr::except($user, ['address']);            // ['name' => 'Anna']
 
data_get($user, 'address.city');            // the same for arrays and objects

Dot notation spares you chains of isset().

Dates

Dates in Laravel are Carbon objects, an extension of the standard date class:

now();                          // the current moment
today();                        // today at 00:00
now()->addDays(3);
now()->subMonth()->startOfMonth();
now()->isWeekend();
 
$post->created_at->format('Y-m-d');
$post->created_at->diffForHumans();   // 3 hours ago

A model turns the created_at and updated_at columns into Carbon by itself. The language of the "3 hours ago" phrase depends on the APP_LOCALE setting.

Numbers

use Illuminate\Support\Number;
 
Number::format(1234567.891, 2);          // 1,234,567.89
Number::currency(1250, 'EUR');           // €1,250.00
Number::percentage(12.5, 1);             // 12.5%
Number::fileSize(5 * 1024 * 1024);       // 5 MB
Number::abbreviate(1500000);             // 2M

Addresses

route('posts.show', $post);     // an address by route name
url('/about');                  // a full address
asset('images/logo.png');       // the address of a file in the public folder

Short accessors

FunctionWhat it returns
auth()->user()The current user
request('page')A value from the request
session('key')A value from the session
config('app.name')A setting
back()A redirect to the previous page
collect([1, 2])A collection from an array
blank($value), filled($value)Whether a value is empty

Debugging

dump($user);        // show the value and continue
dd($user, $posts);  // show and stop the program
 
$posts = Post::where('published', true)->dd();   // show the query

Common mistake

dd() and dump() calls forgotten in the code reach the live site and show visitors internal data — or cut a page off halfway. Search the project for them before every push; the Larastan code analyser can find such calls by itself.

Thanks for reading!

Donate to the site — we work hard for you.