Anvil
Anvil - The mobile companion for Laravel Forge. Available now. Download for iOS

10 Random Laravel Snippets & Methods, Part 3

I write code blocks down that I know I won't use often and will forget about. Every so often I go through them to refresh my memory.

AR
Anthony Rappa
2 min read - 7,577 views -

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

1// Instead of
2Model::where('name', 'foo')->first()->active;
3 
4// Do
5Model::where('name', 'foo')->value('active');
6 
7// Exception if no records found
8Model::where('name', 'foo')->valueOrFail('active');

2. String Masking

1Str::mask('[email protected]', '*', 3);
2// my******************
3 
4Str::mask('+56 9 87654321', '*', -8, 6);
5// + 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:

1<script>
2 var app = <?php echo json_encode($array); ?>;
3</script>

You can do this:

1<script>
2 var app = {{ Js::from($array) }};
3</script>

4. @js

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

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

Will render:

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

5. Checking for debug mode

1if (App::hasDebugModeEnabled()) {
2 // ...
3}

6. Filter Non-null Array Values

1Arr::whereNotNull([null, 0, false, '', null, []]);
2// 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:

1Schema::table('users', function (Blueprint $table) {
2 $table->string('secret')->nullable()->invisible();
3});

This feature is currently only available for MySQL.

8. DateTime Parsing Added to the Request Instance

1// Before
2if ($date = $request->input('when')) {
3 $date = Carbon::parse($datetime);
4}
5 
6// After
7$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:

1Password::defaults(function () {
2 return Password::min(8)
3 ->symbols()
4 ->mixedCase()
5 ->uncompromised()
6 ->rules(new ZxcvbnRule());
7});

10. HTML String Method

1// Before
2new HtmlString(Str::of($content)->markdown());
3 
4// After
5Str::of($content)
6 ->markdown()
7 ->html();

Read next

Exploring PHP 8.5's New Pipe Operator: A Fresh Perspective

Among the exciting features in PHP 8.5, the pipe operator stands out as a game-changing addition to the language's syntax arsenal. This innovative operator transforms how we write sequential operations, making code more intuitive and less nested. Let's dive into this new feature and discover how it can revolutionize your PHP coding practices.

4 min read - 4,439 views -

What's New in Laravel: 8.58 - 8.68

Are you like me and find it impossible to find the time to keep up with the changes in Laravel on a weekly basis? In this series I'll try to roll them up periodically into one post.

AR
3 min read - 9,186 views -