Introducing Laravel Quizzes! Play now

This post is more than a year old. There is a chance the content is outdated.

10 Random Laravel Snippets & Methods, Part 3

10 Random Laravel Snippets & Methods, Part 3

This is the next iteration to the Laravel Snippets Series.

Here are 10 more Laravel snippets/methods I use or have recently saved for later:

1. Get an Eloquent value

// Instead of
Model::where('name', 'foo')->first()->active;

// Do
Model::where('name', 'foo')->value('active');

// Exception if no records found
Model::where('name', 'foo')->valueOrFail('active');

2. String Masking

Str::mask('[email protected]', '*', 3);
// my******************

Str::mask('+56 9 87654321', '*', -8, 6);
// + 56 9 ******21

3. Js::from()

Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable.

Instead of this:

    var app = <?php echo json_encode($array); ?>;

You can do this:

    var app = {{ Js::from($array) }};

4. @js

Building on #3, if you need to render in blade you can use the @js directive.

<div x-data="@js($data)"></div>

Will render:

<div x-data="<?php echo \Illuminate\Support\Js::from($data)->toHtml() ?>"></div>

5. Checking for debug mode

if (App::hasDebugModeEnabled()) {
    // ...

6. Filter Non-null Array Values

Arr::whereNotNull([null, 0, false, '', null, []]);
// returns [0, false, '', []]

7. Invisible Modifier for MySQL Columns

Oliver Matla contributed invisible modifier support, introduced in MySQL v8.0.23. When columns are marked as invisible, they are not implicitly (i.e., SELECT *) and thus not hydrated in Laravel models. These columns can still be explicitly selected, making it useful to omit unless you explicitly need the data:

Schema::table('users', function (Blueprint $table) {

This feature is currently only available for MySQL.

8. DateTime Parsing Added to the Request Instance

// Before
if ($date = $request->input('when')) {
    $date = Carbon::parse($datetime);

// After
$date = $request->date('when');

9. Define Extra Default Password Validation Rules

Ash Allen contributed the ability to define custom validation rules that will run as part of default password rules using the rules() method:

Password::defaults(function () {
    return Password::min(8)
        ->rules(new ZxcvbnRule());

10. HTML String Method

// Before
new HtmlString(Str::of($content)->markdown());

// After
Anthony Rappa

By Anthony Rappa

Hello! I'm a full stack developer from Long Island, New York. Working mainly with Laravel, Tailwind, Livewire, and Alpine.js (TALL Stack). I share everything I know about these tools and more, as well as any useful resources I find from the community. You can find me on GitHub and LinkedIn.