I'm currently available for full time hire! Inquire Here

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

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