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 product5} else {6 // Existing product7}
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 this11public function show($item) {12 abort_unless(Gate::allows('do-thing', $item), 403);13 14 // Actual logic15}16 17// Another use case, make sure the user is logged in18abort_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?popular2 3$request->exists('popular') // true4$request->has('popular') // false5 6http://example.com?popular=foo7 8$request->exists('popular') // true9$request->has('popular') // true
9. @isset
1// From2@if (isset($records))3 // $records is defined and is not null4@endif5 6// To7@isset($records)8 // $records is defined and is not null9@endisset
10. @empty
1// From2@if (empty($records))3 // $records is "empty"4@endif5 6// To7@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// To11@forelse ($users as $user)12 {{ $user->name }}13@empty14 <p>No Users</p>15@endforelse
12. array_wrap()
1$posts = is_array($posts) ? $posts : [$posts];2 3// Same as4$posts = array_wrap($posts);5 6// Inline7foreach (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; // null11$accountId = $user2->account->id ?? null; // null12 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'); // 754$avgCost = data_get($array, 'albums.rock.avg_cost', 0); // 05 6$object->albums->rock->count = 75;7 8$count = data_get($object, 'albums.rock.count'); // 759$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