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.

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

1// Add to AppServiceProvider
2 
3Model::preventLazyLoading(! app()->isProduction());

2. Don't allow unvalidated array keys

1// Add to AppServiceProvider
2 
3Validator::excludeUnvalidatedArrayKeys();

3. Update a model without raising events

1// `updateQuietly` works like `update()` but without raising events
2 
3$user->updateQuietly(['email' => '[email protected]']);

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.

1// Cursor pagination outperforms offset pagination by up to 400X
2 
3$users = User::orderBy('id')->cursorPaginate(10);

5. One of Many Relationships

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

6. firstWhere

1Category::firstWhere('slug', $slug);
2 
3// instead of
4 
5Category::where('slug', $slug)->first();

7. Str::replace

1use Illuminate\Support\Str;
2 
3Str::replace('dead', 'alive', 'PHP is dead');
4 
5/* PHP is alive */
6 
7Str::of('PHP is dead')->replace('dead', 'alive');
8 
9/*
10Illuminate\Support\Stringable {#4091
11 value: "PHP is alive",
12}
13*/

8. Checking if models are the same

1$user = User::find(1);
2$sameUser = User::find(1);
3 
4if ($user->is($sameUser)) {
5 // Same model
6}

9. Don't update timestamps when saving

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

10. tap()

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

1// Returns bool
2$user = $user->update(['name' => 'Anthony']);
3 
4// Updates user and returns original model
5$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:

1// Before
2[
3 'email'=> [
4 Rule::unique('users')->whereNull('deleted_at'),
5 ],
6];
7 
8// After
9[
10 'email'=> [
11 Rule::unique('users')->ignoreTrashed(),
12 ],
13];

12. @class

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

1<span @class([
2 'text-sm',
3 'font-bold' => $active,
4])>
5 Dashboard
6</span>

13. Download Assertions

1// Assert the response returned a download
2$response->assertDownload();
3 
4// Assert the response is a download with a given file name.
5$response->assertDownload('invoice.pdf');

14. Password Validation Rules

1$request->validate([
2 'password' => [
3 'required',
4 'confirmed',
5 Password::min(8)
6 ->mixedCase()
7 ->letters()
8 ->numbers()
9 ->symbols()
10 ->uncompromised(),
11 ],
12]);

15. Assert an input is not present

1$validated = $request->validate([
2 'name' => 'required|max:255',
3 'key' => 'prohibited',
4]);
5 
6// Response: 422
7// 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.