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 4

10 Random Laravel Snippets & Methods, Part 4


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. Reorder orderBy()

If you try to use orderBy on a query that has already been ordered, it will not work since in SQL you can have multiple order by's in a query, so they just end up getting appended.

If you explicitly want to change the ordering, you can use reorder:

1// Consider a relationship
2public function posts()
3{
4 return $this->hasMany(Post::class)->latest();
5}
6 
7// The above already sets the orderBy to `created_at desc` so the following will not override that.
8$user->posts()->orderBy('updated_at', 'desc')->get(); // Still ordered by `created_at desc`
9 
10// Reorder to a different column
11$user->posts()->reorder()->orderBy('updated_at', 'desc')->get(); // Now ordered by `updated_at desc`
12 
13// Or more cleaner
14$user->posts()->reorder('updated_at', 'desc')->get();

2. isDirty()

Check if a model has been modified

1$product = Product::find(1);
2$product->isDirty() // false
3 
4$product->name = "New name";
5$product->isDirty() // true
6$product->isDirty('name') // true

3. @checked

Clean up your markup with the new @checked directive.

From:

1<input type="radio" name="active" value="1" {{ old('active', user->active)) ? 'checked' : '' }} />

To:

1<input type="radio" name="active" value="1" @checked(old('active', user->active)) />

4. @selected

Clean up your markup with the new @selected directive.

1<select name="active">
2 <option value="yes" {{ old('active', user->active)) ? 'selected' : '' }}>Yes</option>
3</select>

To:

1<select name="active">
2 <option value="yes" @selected(old('active', user->active))>Yes</option>
3</select>

5. foreignIdFor()

Instead of using foreignId with a string column, you can specify a model.

1$table->foreignIdFor(\App\Models\Author::class);

6. Route::controller

Laravel 8.80.0 release includes support for defining a common group controller once for a route group, then only providing the methods to the route definitions.

1Route::controller(OrderController::class)->group(function () {
2 Route::get('/orders/{id}', 'show');
3 Route::post('/orders', 'store');
4});

7. make:migration strings

From:

1php artisan make:migration create_users_table

To:

1php artisan make:migration "create users table"

8. Mail::alwaysTo()

Avoiding Accidental Email Sends with alwaysTo()

1// AppServiceProvider.php
2if (! app()->environment('production')) {
3 Mail::alwaysTo('[email protected]');
4}

9. str()

The str function returns a new Illuminate\Support\Stringable instance of the given string. This function is equivalent to the Str::of method:

1$string = str('Taylor')->append(' Otwell');
2 
3// 'Taylor Otwell'

10. skip() TransformRequests-type middleware

As of @laravelphp v8.36.0, you can skip 'TransformRequests' middlewares by registering a callback.

For example, you can use it on 'TrimStrings' and 'ConvertEmptyStringsToNull'

1ConvertEmptyStringsToNull::skipWhen(
2 fn (Request $request) => $request->is('admin/*')
3);
4 
5TrimStrings::skipWhen(
6 fn (Request $request) => $request->is('admin/*')
7);
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.