This post is more than a year old. There is a chance the content is outdated.

15 Random Laravel Snippets & Methods

15 Random Laravel Snippets & Methods


Most of these are probably common knowledge, but 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.

Here are 15 Laravel snippets/methods I found scrolling through my SnippetsLab:

1. Determining if the record on firstOrCreate was new or not

1$product = Product::firstOrCreate(...)
2 
3if ($product->wasRecentlyCreated()) {
4 // New product
5} else {
6 // Existing product
7}

2. Find related IDs on a BelongsToMany Relationship

1$user->roles()->allRelatedIds()->toArray();

3. abort_unless()

1// Instead of
2public function show($item) {
3 if (// User can not do this thing) {
4 return false;
5 }
6 
7 // Else do this
8}
9 
10// Do this
11public function show($item) {
12 abort_unless(Gate::allows('do-thing', $item), 403);
13 
14 // Actual logic
15}
16 
17// Another use case, make sure the user is logged in
18abort_unless(Auth::check(), 403);

4. Model Keys

1User::all()->pluck('id')->toArray();
2 
3// In most cases, however, this can be shortened. Like this:
4 
5User::all()->modelKeys();

5. throw_if()

1throw_if(
2 !Hash::check($data['current_password'], $user->password),
3 new Exception(__('That is not your old password.'))
4);

6. Dump all columns of a table

1Schema::getColumnListing('table')

7. Redirect to external domains

1return redirect()->away('https://www.google.com');

8. Request exists() vs has()

1// http://example.com?popular
2 
3$request->exists('popular') // true
4$request->has('popular') // false
5 
6http://example.com?popular=foo
7 
8$request->exists('popular') // true
9$request->has('popular') // true

9. @isset

1// From
2@if (isset($records))
3 // $records is defined and is not null
4@endif
5 
6// To
7@isset($records)
8 // $records is defined and is not null
9@endisset

10. @empty

1// From
2@if (empty($records))
3 // $records is "empty"
4@endif
5 
6// To
7@empty($records)
8 // $records is "empty"
9@endempty

11. @forelse

1// From
2@if ($users->count())
3 @foreach ($users as $user)
4 
5 @endforeach
6@else
7 
8@endif
9 
10// To
11@forelse ($users as $user)
12 {{ $user->name }}
13@empty
14 <p>No Users</p>
15@endforelse

12. array_wrap()

1$posts = is_array($posts) ? $posts : [$posts];
2 
3// Same as
4$posts = array_wrap($posts);
5 
6// Inline
7foreach (array_wrap($posts) as $post) {
8 // ..
9}

13. optional()

The optional() helper allows you to access properties or call methods on an object. If the given object is null, properties and methods will return null instead of causing an error.

1// User 1 exists, with account
2$user1 = User::find(1);
3$accountId = $user1->account->id; // 123
4 
5// User 2 exists, without account
6$user2 = User::find(2);
7$accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
8 
9// Fix without optional()
10$accountId = $user2->account ? $user2->account->id : null; // null
11$accountId = $user2->account->id ?? null; // null
12 
13// Fix with optional()
14$accountId = optional($user2->account)->id; // null

14. data_get()

The data_get() helper allows you to get a value from an array or object with dot notation. This functions similarly to array_get() as well. The optional third parameter can be used to supply a default value if the key is not found.

1$array = ['albums' => ['rock' => ['count' => 75]]];
2 
3$count = data_get($array, 'albums.rock.count'); // 75
4$avgCost = data_get($array, 'albums.rock.avg_cost', 0); // 0
5 
6$object->albums->rock->count = 75;
7 
8$count = data_get($object, 'albums.rock.count'); // 75
9$avgCost = data_get($object, 'albums.rock.avg_cost', 0); // 0

15. push()

You can save a model and its corresponding relationships using the push() method.

1$user = User::first();
2$user->name = "Peter";
3 
4$user->phone->number = '1234567890';
5 
6$user->push(); // This will update both user and phone record in DB
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.