Introducing Laravel Quizzes! Play now

15 Random Laravel Snippets & Methods, Part 2

15 Random Laravel Snippets & Methods, Part 2


This is a follow up to the original 15 Random Laravel Snippets & Methods post.

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

1. Prevent N+1 with an Exception

// Add to AppServiceProvider

Model::preventLazyLoading(! app()->isProduction());

2. Don't allow unvalidated array keys

// Add to AppServiceProvider

Validator::excludeUnvalidatedArrayKeys();

3. Update a model without raising events

// `updateQuietly` works like `update()` but without raising events

$user->updateQuietly(['email' => 'user@example.com']);

4. Cursor Pagination

The main difference between offset and cursor pagination is that offset pagination uses an offset clause while cursor pagination uses a where clause with a comparison operator.

// Cursor pagination outperforms offset pagination by up to 400X

$users = User::orderBy('id')->cursorPaginate(10);

5. One of Many Relationships

/**
 * Get the user's most recent order.
 */
public function latestOrder()
{
    return $this->hasOne(Order::class)->latestOfMany();
}

6. firstWhere

Category::firstWhere('slug', $slug);

// instead of 

Category::where('slug', $slug)->first();

7. Str::replace

use Illuminate\Support\Str;

Str::replace('dead', 'alive', 'PHP is dead');

/* PHP is alive */

Str::of('PHP is dead')->replace('dead', 'alive');

/*
Illuminate\Support\Stringable {#4091
    value: "PHP is alive",
}
*/

8. Checking if models are the same

$user = User::find(1);
$sameUser = User::find(1);

if ($user->is($sameUser)) {
    // Same model
}

9. Don't update timestamps when saving

$user->save(['timestamps' => false]);

10. tap()

Force any method on an object to return the object itself.

// Returns bool
$user = $user->update(['name' => 'Anthony']);

// Updates user and returns original model
$user = tap($user)->update(['name' => 'Anthony']);

11. Ignore Trashed Models in Unique Validation Rule

Philo Hermans contributed a ignoreTrashed() validation rule which is syntactic sugar for the following rule:

// Before
[
    'email'=> [
        Rule::unique('users')->whereNull('deleted_at'),
    ],
];
 
// After
[
    'email'=> [
        Rule::unique('users')->ignoreTrashed(),
    ],
];

12. @class

Dan Harrin contributed a @class Blade directive that allows developers to use conditional classes on any HTML element:

<span @class([
    'text-sm',
    'font-bold' => $active,
])>
    Dashboard
</span>

13. Download Assertions

// Assert the response returned a download
$response->assertDownload();

// Assert the response is a download with a given file name.
$response->assertDownload('invoice.pdf');

14. Password Validation Rules

$request->validate([
    'password' => [
        'required', 
        'confirmed', 
        Password::min(8)
            ->mixedCase()
            ->letters()
            ->numbers()
            ->symbols()
            ->uncompromised(),
    ],
]);

15. Assert an input is not present

$validated = $request->validate([
    'name' => 'required|max:255',
    'key' => 'prohibited',
]);

// Response: 422
// The key field is prohibited
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.