You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: artisan.md
+28-8Lines changed: 28 additions & 8 deletions
Original file line number
Diff line number
Diff line change
@@ -25,7 +25,7 @@ Artisan is the command-line interface included with Laravel. It provides a numbe
25
25
26
26
php artisan list
27
27
28
-
Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, simply precede the name of the command with `help`:
28
+
Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, precede the name of the command with `help`:
29
29
30
30
php artisan help migrate
31
31
@@ -54,7 +54,7 @@ After generating your command, you should fill in the `signature` and `descripti
54
54
55
55
> {tip} For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example below, note that we inject a service class to do the "heavy lifting" of sending the e-mails.
56
56
57
-
Let's take a look at an example command. Note that we are able to inject any dependencies we need into the command's constructor. The Laravel [service container](/docs/{{version}}/container) will automatically inject all dependencies type-hinted in the constructor:
57
+
Let's take a look at an example command. Note that we are able to inject any dependencies we need into the command's constructor or `handle` method. The Laravel [service container](/docs/{{version}}/container) will automatically inject all dependencies type-hinted in the constructor or `handle` method:
58
58
59
59
<?php
60
60
@@ -321,9 +321,9 @@ The `anticipate` method can be used to provide auto-completion for possible choi
321
321
322
322
#### Multiple Choice Questions
323
323
324
-
If you need to give the user a predefined set of choices, you may use the `choice` method. You may set the default value to be returned if no option is chosen:
324
+
If you need to give the user a predefined set of choices, you may use the `choice` method. You may set the array index of the default value to be returned if no option is chosen:
325
325
326
-
$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);
326
+
$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $defaultIndex);
327
327
328
328
<aname="writing-output"></a>
329
329
### Writing Output
@@ -365,6 +365,8 @@ For long running tasks, it could be helpful to show a progress indicator. Using
@@ -374,7 +376,7 @@ For long running tasks, it could be helpful to show a progress indicator. Using
374
376
375
377
$bar->finish();
376
378
377
-
For more advanced options, check out the [Symfony Progress Bar component documentation](https://symfony.com/doc/2.7/components/console/helpers/progressbar.html).
379
+
For more advanced options, check out the [Symfony Progress Bar component documentation](https://symfony.com/doc/current/components/console/helpers/progressbar.html).
378
380
379
381
<aname="registering-commands"></a>
380
382
## Registering Commands
@@ -394,7 +396,7 @@ Because of the `load` method call in your console kernel's `commands` method, al
394
396
// ...
395
397
}
396
398
397
-
You may also manually register commands by adding its class name to the `$command` property of your `app/Console/Kernel.php` file. When Artisan boots, all the commands listed in this property will be resolved by the [service container](/docs/{{version}}/container) and registered with Artisan:
399
+
You may also manually register commands by adding its class name to the `$commands` property of your `app/Console/Kernel.php` file. When Artisan boots, all the commands listed in this property will be resolved by the [service container](/docs/{{version}}/container) and registered with Artisan:
398
400
399
401
protected $commands = [
400
402
Commands\SendEmails::class
@@ -403,7 +405,7 @@ You may also manually register commands by adding its class name to the `$comman
403
405
<aname="programmatically-executing-commands"></a>
404
406
## Programmatically Executing Commands
405
407
406
-
Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the `call` method on the `Artisan` facade to accomplish this. The `call` method accepts the name of the command as the first argument, and an array of command parameters as the second argument. The exit code will be returned:
408
+
Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the `call` method on the `Artisan` facade to accomplish this. The `call` method accepts either the command's name or class as the first argument, and an array of command parameters as the second argument. The exit code will be returned:
407
409
408
410
Route::get('/foo', function () {
409
411
$exitCode = Artisan::call('email:send', [
@@ -423,7 +425,25 @@ Using the `queue` method on the `Artisan` facade, you may even queue Artisan com
423
425
//
424
426
});
425
427
426
-
If you need to specify the value of an option that does not accept string values, such as the `--force` flag on the `migrate:refresh` command, you may pass `true` or `false`:
428
+
You may also specify the connection or queue the Artisan command should be dispatched to:
429
+
430
+
Artisan::queue('email:send', [
431
+
'user' => 1, '--queue' => 'default'
432
+
])->onConnection('redis')->onQueue('commands');
433
+
434
+
#### Passing Array Values
435
+
436
+
If your command defines an option that accepts an array, you may pass an array of values to that option:
437
+
438
+
Route::get('/foo', function () {
439
+
$exitCode = Artisan::call('email:send', [
440
+
'user' => 1, '--id' => [5, 13]
441
+
]);
442
+
});
443
+
444
+
#### Passing Boolean Values
445
+
446
+
If you need to specify the value of an option that does not accept string values, such as the `--force` flag on the `migrate:refresh` command, you should pass `true` or `false`:
> {tip} **Want to get started fast?** Just run `php artisan make:auth` and `php artisan migrate` in a fresh Laravel application. Then, navigate your browser to `http://your-app.dev/register` or any other URL that is assigned to your application. These two commands will take care of scaffolding your entire authentication system!
30
+
> {tip} **Want to get started fast?** Just run `php artisan make:auth` and `php artisan migrate` in a fresh Laravel application. Then, navigate your browser to `http://your-app.test/register` or any other URL that is assigned to your application. These two commands will take care of scaffolding your entire authentication system!
28
31
29
32
Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at `config/auth.php`, which contains several well documented options for tweaking the behavior of the authentication services.
30
33
@@ -67,14 +70,16 @@ The `make:auth` command will also create a `resources/views/layouts` directory c
67
70
<aname="included-authenticating"></a>
68
71
### Authenticating
69
72
70
-
Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may simply access your application in a browser since the authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.
73
+
Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may access your application in a browser since the authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.
71
74
72
75
#### Path Customization
73
76
74
-
When a user is successfully authenticated, they will be redirected to the `/home` URI. You can customize the post-authentication redirect location by defining a `redirectTo` property on the `LoginController`, `RegisterController`, and `ResetPasswordController`:
77
+
When a user is successfully authenticated, they will be redirected to the `/home` URI. You can customize the post-authentication redirect location by defining a `redirectTo` property on the `LoginController`, `RegisterController`, `ResetPasswordController`, and `VerificationController`:
75
78
76
79
protected $redirectTo = '/';
77
80
81
+
Next, you should modify the `RedirectIfAuthenticated` middleware's `handle` method to use your new URI when redirecting the user.
82
+
78
83
If the redirect path needs custom generation logic you may define a `redirectTo` method instead of a `redirectTo` property:
79
84
80
85
protected function redirectTo()
@@ -175,6 +180,21 @@ Of course, if you are using [controllers](/docs/{{version}}/controllers), you ma
175
180
$this->middleware('auth');
176
181
}
177
182
183
+
#### Redirecting Unauthenticated Users
184
+
185
+
When the `auth` middleware detects an unauthorized user, it will redirect the user to the `login`[named route](/docs/{{version}}/routing#named-routes). You may modify this behavior by updating the `redirectTo` function in your `app/Http/Middleware/Authenticate.php` file:
186
+
187
+
/**
188
+
* Get the path the user should be redirected to.
189
+
*
190
+
* @param \Illuminate\Http\Request $request
191
+
* @return string
192
+
*/
193
+
protected function redirectTo($request)
194
+
{
195
+
return route('login');
196
+
}
197
+
178
198
#### Specifying A Guard
179
199
180
200
When attaching the `auth` middleware to a route, you may also specify which guard should be used to authenticate the user. The guard specified should correspond to one of the keys in the `guards` array of your `auth.php` configuration file:
@@ -200,25 +220,30 @@ We will access Laravel's authentication services via the `Auth` [facade](/docs/{
200
220
201
221
namespace App\Http\Controllers;
202
222
223
+
use Illuminate\Http\Request;
203
224
use Illuminate\Support\Facades\Auth;
204
225
205
226
class LoginController extends Controller
206
227
{
207
228
/**
208
229
* Handle an authentication attempt.
209
230
*
231
+
* @param \Illuminate\Http\Request $request
232
+
*
210
233
* @return Response
211
234
*/
212
-
public function authenticate()
235
+
public function authenticate(Request $request)
213
236
{
214
-
if (Auth::attempt(['email' => $email, 'password' => $password])) {
The `attempt` method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the `email` column. If the user is found, the hashed password stored in the database will be compared with the hashed `password` value passed to the method via the array. If the two hashed passwords match an authenticated session will be started for the user.
246
+
The `attempt` method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the `email` column. If the user is found, the hashed password stored in the database will be compared with the `password` value passed to the method via the array. You should not hash the password specified as the `password` value, since the framework will automatically hash the value before comparing it to the hashed password in the database. If the two hashed passwords match an authenticated session will be started for the user.
222
247
223
248
The `attempt` method will return `true` if authentication was successful. Otherwise, `false` will be returned.
224
249
@@ -285,7 +310,7 @@ Of course, you may specify the guard instance you would like to use:
285
310
286
311
#### Authenticate A User By ID
287
312
288
-
To log a user into the application by their ID, you may use the `loginUsingId` method. This method simply accepts the primary key of the user you wish to authenticate:
313
+
To log a user into the application by their ID, you may use the `loginUsingId` method. This method accepts the primary key of the user you wish to authenticate:
289
314
290
315
Auth::loginUsingId(1);
291
316
@@ -325,7 +350,7 @@ You may also use HTTP Basic Authentication without setting a user identifier coo
325
350
326
351
<?php
327
352
328
-
namespace Illuminate\Auth\Middleware;
353
+
namespace App\Http\Middleware;
329
354
330
355
use Illuminate\Support\Facades\Auth;
331
356
@@ -351,10 +376,38 @@ Next, [register the route middleware](/docs/{{version}}/middleware#registering-m
351
376
// Only authenticated users may enter...
352
377
})->middleware('auth.basic.once');
353
378
379
+
<aname="logging-out"></a>
380
+
## Logging Out
381
+
382
+
To manually log users out of your application, you may use the `logout` method on the `Auth` facade. This will clear the authentication information in the user's session:
Laravel also provides a mechanism for invalidating and "logging out" a user's sessions that are active on other devices without invalidating the session on their current device. Before getting started, you should make sure that the `Illuminate\Session\Middleware\AuthenticateSession` middleware is present and un-commented in your `app/Http/Kernel.php` class' `web` middleware group:
Then, you may use the `logoutOtherDevices` method on the `Auth` facade. This method requires the user to provide their current password, which your application should accept through an input form:
400
+
401
+
use Illuminate\Support\Facades\Auth;
402
+
403
+
Auth::logoutOtherDevices($password);
404
+
405
+
> {note} When the `logoutOtherDevices` method is invoked, the user's other sessions will be invalidated entirely, meaning they will be "logged out" of all guards they were previously authenticated by.
406
+
354
407
<aname="adding-custom-guards"></a>
355
408
## Adding Custom Guards
356
409
357
-
You may define your own authentication guards using the `extend` method on the `Auth` facade. You should place this call to `provider` within a [service provider](/docs/{{version}}/providers). Since Laravel already ships with an `AuthServiceProvider`, we can place the code in that provider:
410
+
You may define your own authentication guards using the `extend` method on the `Auth` facade. You should place this call to `extend` within a [service provider](/docs/{{version}}/providers). Since Laravel already ships with an `AuthServiceProvider`, we can place the code in that provider:
358
411
359
412
<?php
360
413
@@ -392,6 +445,39 @@ As you can see in the example above, the callback passed to the `extend` method
392
445
],
393
446
],
394
447
448
+
<aname="closure-request-guards"></a>
449
+
### Closure Request Guards
450
+
451
+
The simplest way to implement a custom, HTTP request based authentication system is by using the `Auth::viaRequest` method. This method allows you to quickly define your authentication process using a single Closure.
452
+
453
+
To get started, call the `Auth::viaRequest` method within the `boot` method of your `AuthServiceProvider`. The `viaRequest` method accepts a guard name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a Closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, `null`:
454
+
455
+
use App\User;
456
+
use Illuminate\Http\Request;
457
+
use Illuminate\Support\Facades\Auth;
458
+
459
+
/**
460
+
* Register any application authentication / authorization services.
461
+
*
462
+
* @return void
463
+
*/
464
+
public function boot()
465
+
{
466
+
$this->registerPolicies();
467
+
468
+
Auth::viaRequest('custom-token', function ($request) {
Once your custom guard has been defined, you may use this guard in the `guards` configuration of your `auth.php` configuration file:
474
+
475
+
'guards' => [
476
+
'api' => [
477
+
'driver' => 'custom-token',
478
+
],
479
+
],
480
+
395
481
<aname="adding-custom-user-providers"></a>
396
482
## Adding Custom User Providers
397
483
@@ -466,7 +552,7 @@ The `retrieveById` function typically receives a key representing the user, such
466
552
467
553
The `retrieveByToken` function retrieves a user by their unique `$identifier` and "remember me" `$token`, stored in a field `remember_token`. As with the previous method, the `Authenticatable` implementation should be returned.
468
554
469
-
The `updateRememberToken` method updates the `$user` field `remember_token` with the new `$token`. The new token can be either a fresh token, assigned on a successful "remember me" login attempt, or when the user is logging out.
555
+
The `updateRememberToken` method updates the `$user` field `remember_token` with the new `$token`. A fresh token is assigned on a successful "remember me" login attempt or when the user is logging out.
470
556
471
557
The `retrieveByCredentials` method receives the array of credentials passed to the `Auth::attempt` method when attempting to sign into an application. The method should then "query" the underlying persistent storage for the user matching those credentials. Typically, this method will run a query with a "where" condition on `$credentials['username']`. The method should then return an implementation of `Authenticatable`. **This method should not attempt to do any password validation or authentication.**
472
558
@@ -475,7 +561,7 @@ The `validateCredentials` method should compare the given `$user` with the `$cre
475
561
<aname="the-authenticatable-contract"></a>
476
562
### The Authenticatable Contract
477
563
478
-
Now that we have explored each of the methods on the `UserProvider`, let's take a look at the `Authenticatable` contract. Remember, the provider should return implementations of this interface from the `retrieveById` and `retrieveByCredentials` methods:
564
+
Now that we have explored each of the methods on the `UserProvider`, let's take a look at the `Authenticatable` contract. Remember, the provider should return implementations of this interface from the `retrieveById`, `retrieveByToken`, and `retrieveByCredentials` methods:
479
565
480
566
<?php
481
567
@@ -532,4 +618,8 @@ Laravel raises a variety of [events](/docs/{{version}}/events) during the authen
0 commit comments