Skip to content

Commit

Permalink
Formatting, syntax fixes, typos
Browse files Browse the repository at this point in the history
  • Loading branch information
mc0de committed Oct 17, 2022
1 parent f4b2bfa commit 60feba0
Show file tree
Hide file tree
Showing 15 changed files with 547 additions and 159 deletions.
16 changes: 11 additions & 5 deletions Api.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
- [Sorting Your API Results](#sorting-your-api-results)
- [Customize Exception Handler](#customize-exception-handler-for-api)


### API Resources: With or Without "data"?

If you use Eloquent API Resources to return data, they will be automatically wrapped in 'data'. If you want to remove it, add `JsonResource::withoutWrapping();` in `app/Providers/AppServiceProvider.php`.
Expand Down Expand Up @@ -43,9 +42,13 @@ public function reorder(Request $request)
```

### Avoid N+1 queries in API resources
You can avoid N+1 queries in API resources by using the `whenLoaded()` method.<br>
This will only append the department if it’s already loaded in the Employee model.<br>

You can avoid N+1 queries in API resources by using the `whenLoaded()` method.

This will only append the department if it’s already loaded in the Employee model.

Without `whenLoaded()` there is always a query for the department

```php
class EmplyeeResource extends JsonResource
{
Expand All @@ -65,7 +68,9 @@ class EmplyeeResource extends JsonResource
Tip given by [@mmartin_joo](https://twitter.com/mmartin_joo/status/1473987501501071362)

### Get Bearer Token from Authorization header

The `bearerToken()` function is very handy when you are working with apis & want to access the token from Authorization header.

```php
// Don't parse API headers manually like this:
$tokenWithBearer = $request->header('Authorization');
Expand Down Expand Up @@ -124,6 +129,7 @@ Route::get('dogs', function (Request $request) {
### Customize Exception Handler For API

#### Laravel 8 and below:

There's a method `render()` in `App\Exceptions` class:

```php
Expand Down Expand Up @@ -151,13 +157,13 @@ There's a method `render()` in `App\Exceptions` class:
}
```

#### Laravel 8 and above:
#### Laravel 9 and above:

There's a method `register()` in `App\Exceptions` class:

```php
public function register()
{

$this->renderable(function (ModelNotFoundException $e, $request) {
if ($request->wantsJson() || $request->is('api/*')) {
return response()->json(['message' => 'Item Not Found'], 404);
Expand Down
11 changes: 9 additions & 2 deletions Artisan.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
- [Hide your custom command](#hide-your-custom-command)
- [Skip method](#skip-method)


### Artisan command parameters

When creating Artisan command, you can ask the input in variety of ways: `$this->confirm()`, `$this->anticipate()`, `$this->choice()`.
Expand All @@ -31,13 +30,15 @@ $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $defaultIndex);
### Maintenance Mode

If you want to enable maintenance mode on your page, execute the down Artisan command:

```bash
php artisan down
```

Then people would see default 503 status page.

You may also provide flags, in Laravel 8:

- the path the user should be redirected to
- the view that should be prerendered
- secret phrase to bypass maintenance mode
Expand All @@ -49,6 +50,7 @@ php artisan down --redirect="/" --render="errors::503" --secret="1630542a-246b-4
```

Before Laravel 8:

- message that would be shown
- retry page reload every X seconds
- still allow the access to some IP address
Expand All @@ -58,6 +60,7 @@ php artisan down --message="Upgrading Database" --retry=60 --allow=127.0.0.1
```

When you've done the maintenance work, just run:

```bash
php artisan up
```
Expand Down Expand Up @@ -107,7 +110,9 @@ Route::get('/foo', function () {
```

### Hide your custom command

If you don't want to show a specific command on the artisan command list, set `hidden` property to `true`

```php
class SendMail extends Command
{
Expand All @@ -121,9 +126,11 @@ You won't see `send:mail` on the available commands if you typed `php artisan`
Tip given by [@sky_0xs](https://twitter.com/sky_0xs/status/1487921500023832579)

### Skip method
Laravel the skip method in scheduler<br>

Laravel the skip method in scheduler

You can use `skip` in your commands to skip an execution

```php
$schedule->command('emails:send')->daily()->skip(function () {
return Calendar::isHoliday();
Expand Down
3 changes: 2 additions & 1 deletion Auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ if (Auth::once($credentials)) {
It's convenient to change the user's API Token when its password changes.

Model:

```php
public function setPasswordAttribute($value)
{
Expand All @@ -79,4 +80,4 @@ Gate::before(function($user, $ability) {
return true;
}
});
```
```
18 changes: 12 additions & 6 deletions Collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
If you want to group result by some condition which isn’t a direct column in your database, you can do that by providing a closure function.

For example, if you want to group users by day of registration, here’s the code:

```php
$users = User::all()->groupBy(function($item) {
return $item->created_at->format('Y-m-d');
Expand All @@ -27,6 +28,7 @@ $users = User::all()->groupBy(function($item) {
### Multiple Collection Methods in a Row

If you query all results with `->all()` or `->get()`, you may then perform various Collection operations on the same result, it won’t query database every time.

```php
$users = User::all();
echo 'Max ID: ' . $users->max('id');
Expand All @@ -36,8 +38,7 @@ echo 'Total budget: ' . $users->sum('budget');

### Calculate Sum with Pagination

How to calculate the sum of all records when you have only the PAGINATED collection? Do the calculation BEFORE the pagination, but from the same query.

How to calculate the sum of all records when you have only the PAGINATED collection? Do the calculation BEFORE the pagination, but from the same query.

```php
// How to get sum of post_views with pagination?
Expand All @@ -54,6 +55,7 @@ $posts = $query->paginate(10);
```

### Serial no in foreach loop with pagination

We can use foreach collection items index as serial no (SL) in pagination.

```php
Expand All @@ -66,11 +68,12 @@ We can use foreach collection items index as serial no (SL) in pagination.
...
@endforeach
```

it will solve the issue of next pages(?page=2&...) index count from continue.

### Higher order collection methods

Collections have higher order methods, this are methods that can be chained , like `groupBy()` , `map()` ... Giving you a fluid syntax. This example calculates the
Collections have higher order methods, this are methods that can be chained , like `groupBy()` , `map()` ... Giving you a fluid syntax. This example calculates the
price per group of products on an offer.

```php
Expand All @@ -85,8 +88,8 @@ $offer = [
['group' => 3, 'price' => 60]
]
];
$totalPerGroup = collect($offer['lines'])->groupBy('group')->map(fn($group) => $group->sum('price'));

$totalPerGroup = collect($offer['lines'])->groupBy('group')->map(fn($group) => $group->sum('price'));
```

### Higher order collection message
Expand All @@ -106,12 +109,14 @@ $offer = [
['group' => 3, 'price' => 60]
]
];

$totalPerGroup = collect($offer['lines'])->groupBy->group->map->sum('price');
```

### Get an existing key or insert a value if it doesn't exist and return the value

In Laravel 8.81 `getOrPut` method to Collections that simplifies the use-case where you want to either get an existing key or insert a value if it doesn't exist and return the value.

```php
$key = 'name';
// Still valid
Expand All @@ -131,6 +136,7 @@ return $this->collection->getOrPut($key, $value='teacoders');
Tip given by [@Teacoders](https://twitter.com/Teacoders/status/1488338815592718336)

### Static times method

The static times method creates a new collection by invoking the given closure a specified number of times.

```php
Expand Down
Loading

0 comments on commit 60feba0

Please sign in to comment.