Generating Events & Listeners

Of course, manually creating the files for each event and listener is cumbersome. Instead, add listeners and events to your EventServiceProvider and use the event:generate command. This command will generate any events or listeners that are listed in your EventServiceProvider. Of course, events and listeners that already exist will be left untouched:

php artisan event:generate

Manually Registering Events
Typically, events should be registered via the EventServiceProvider $listen array; however, you may also register Closure based events manually in the boot method of your EventServiceProvider:

/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();

Event::listen(‘event.name’, function ($foo, $bar) {
//
});
}
Wildcard Event Listeners
You may even register listeners using the * as a wildcard parameter, allowing you to catch multiple events on the same listener. Wildcard listeners receive the event name as their first argument, and the entire event data array as their second argument:

Event::listen(‘event.*’, function ($eventName, array $data) {
//
});

Defining Events
An event class is a data container which holds the information related to the event. For example, let’s assume our generated OrderShipped event receives an Eloquent ORM object:

namespace App\Events;

use App\Order;
use Illuminate\Queue\SerializesModels;

class OrderShipped
{
    use SerializesModels;

    public $order;

    /**
     * Create a new event instance.
     *
     * @param  \App\Order  $order
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }
}

As you can see, this event class contains no logic. It is a container for the Order instance that was purchased. The SerializesModels trait used by the event will gracefully serialize any Eloquent models if the event object is serialized using PHP’s serialize function.

Defining Listeners
Next, let’s take a look at the listener for our example event. Event listeners receive the event instance in their handle method. The event:generate command will automatically import the proper event class and type-hint the event on the handle method. Within the handle method, you may perform any actions necessary to respond to the event:

namespace App\Listeners;

use App\Events\OrderShipped;

class SendShipmentNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    public function handle(OrderShipped $event)
    {
        // Access the order using $event->order...
    }
}

Stopping The Propagation Of An Event
Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener’s handle method.

Queued Event Listeners
Queueing listeners can be beneficial if your listener is going to perform a slow task such as sending an e-mail or making an HTTP request. Before getting started with queued listeners, make sure to configure your queue and start a queue listener on your server or local development environment.

To specify that a listener should be queued, add the ShouldQueue interface to the listener class. Listeners generated by the event:generate Artisan command already have this interface imported into the current namespace, so you can use it immediately:

namespace App\Listeners;

use App\Events\OrderShipped;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendShipmentNotification implements ShouldQueue
{
    //
}

That’s it! Now, when this listener is called for an event, it will be automatically queued by the event dispatcher using Laravel’s queue system. If no exceptions are thrown when the listener is executed by the queue, the queued job will automatically be deleted after it has finished processing.

Customizing The Queue Connection & Queue Name
If you would like to customize the queue connection and queue name used by an event listener, you may define $connection and $queue properties on your listener class:

namespace App\Listeners;

use App\Events\OrderShipped;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendShipmentNotification implements ShouldQueue
{
    /**
     * The name of the connection the job should be sent to.
     *
     * @var string|null
     */
    public $connection = 'sqs';

    /**
     * The name of the queue the job should be sent to.
     *
     * @var string|null
     */
    public $queue = 'listeners';
}

Manually Accessing The Queue
If you need to manually access the listener’s underlying queue job’s delete and release methods, you may do so using the Illuminate\Queue\InteractsWithQueue trait. This trait is imported by default on generated listeners and provides access to these methods:

namespace App\Listeners;

use App\Events\OrderShipped;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderShipped  $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        if (true) {
            $this->release(30);
        }
    }
}

Handling Failed Jobs
Sometimes your queued event listeners may fail. If queued listener exceeds the maximum number of attempts as defined by your queue worker, the failed method will be called on your listener. The failed method receives the event instance and the exception that caused the failure:

namespace App\Listeners;

use App\Events\OrderShipped;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderShipped  $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        //
    }

    /**
     * Handle a job failure.
     *
     * @param  \App\Events\OrderShipped  $event
     * @param  \Exception  $exception
     * @return void
     */
    public function failed(OrderShipped $event, $exception)
    {
        //
    }
}

Dispatching Events
To dispatch an event, you may pass an instance of the event to the event helper. The helper will dispatch the event to all of its registered listeners. Since the event helper is globally available, you may call it from anywhere in your application:

namespace App\Http\Controllers;

use App\Order;
use App\Events\OrderShipped;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    /**
     * Ship the given order.
     *
     * @param  int  $orderId
     * @return Response
     */
    public function ship($orderId)
    {
        $order = Order::findOrFail($orderId);

        // Order shipment logic...

        event(new OrderShipped($order));
    }
}

Event Subscribers
Writing Event Subscribers
Event subscribers are classes that may subscribe to multiple events from within the class itself, allowing you to define several event handlers within a single class. Subscribers should define a subscribe method, which will be passed an event dispatcher instance. You may call the listen method on the given dispatcher to register event listeners:

namespace App\Listeners;

class UserEventSubscriber
{
    /**
     * Handle user login events.
     */
    public function onUserLogin($event) {}

    /**
     * Handle user logout events.
     */
    public function onUserLogout($event) {}

    /**
     * Register the listeners for the subscriber.
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'Illuminate\Auth\Events\Login',
            'App\Listeners\UserEventSubscriber@onUserLogin'
        );

        $events->listen(
            'Illuminate\Auth\Events\Logout',
            'App\Listeners\UserEventSubscriber@onUserLogout'
        );
    }
}

Larvel Event

Laravel’s events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. Don’t worry if you don’t see these directories in your application, since they will be created for you as you generate events and listeners using Artisan console commands.

Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an OrderShipped event, which a listener can receive and transform into a Slack notification.

Registering Events & Listeners
The EventServiceProvider included with your Laravel application provides a convenient place to register all of your application’s event listeners. The listen property contains an array of all events (keys) and their listeners (values). Of course, you may add as many events to this array as your application requires. For example, let’s add a OrderShipped event:

protected $listen = [
    'App\Events\OrderShipped' => [
        'App\Listeners\SendShipmentNotification',
    ],
];

Laravel Collections

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We’ll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:
コレクションは普通の文法です。laravelにサポートされてるんですね。

$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
    return strtoupper($name);
})
->reject(function ($name) {
    return empty($name);
});

As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.

Creating Collections
As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as:

$collection = collect([1, 2, 3]);

Extending Collections
Collections are “macroable”, which allows you to add additional methods to the Collection class at run time. For example, the following code adds a toUpper method to the Collection class:

use Illuminate\Support\Str;

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return Str::upper($value);
    });
});

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

Available Methods
For the remainder of this documentation, we’ll discuss each method available on the Collection class. Remember, all of these methods may be chained to fluently manipulate the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:
うわ、すげーある。
allaverageavgchunkcollapsecombineconcatcontainscontainsStrictcountcrossJoindddiffdiffAssocdiffKeysdumpeacheachSpreadeveryexceptfilterfirstfirstWhereflatMapflattenflipforgetforPagegetgroupByhasimplodeintersectintersectByKeysisEmptyisNotEmptykeyBykeyslastmacromakemapmapIntomapSpreadmapToGroupsmapWithKeysmaxmedianmergeminmodenthonlypadpartitionpipepluckpopprependpullpushputrandomreducerejectreversesearchshiftshuffleslicesortsortBysortByDescsortKeyssortKeysDescsplicesplitsumtaketaptimestoArraytoJsontransformunionuniqueuniqueStrictunlessunwrapvalueswhenwherewhereStrictwhereInwhereInStrictwhereInstanceOfwhereNotInwhereNotInStrictwrapzip

Method Listing
これ全部やる気か。プログラマーってすごいね。って、中身見ると普通だな。

collect([1, 2, 3])->all();
$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
$average = collect([1, 1, 2, 4])->avg();
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach
$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
$collapsed = $collection->collapse();
$collapsed->all();
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
$collection->contains('New York');
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
    return $value > 5;
});
$collection = collect([1, 2, 3, 4]);
$collection->count();
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
$matrix->all();
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
$collection = collect([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6
]);
$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6
]);
$diff->all();
$collection->each(function ($item, $key) {
});
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();

Higher Order Messages
Collections also provide support for “higher order messages”, which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: average, avg, contains, each, every, filter, first, flatMap, groupBy, keyBy, map, max, min, partition, reject, sortBy, sortByDesc, sum, and unique.

Each higher order message can be accessed as a dynamic property on a collection instance. For instance, let’s use the each higher order message to call a method on each object within a collection:

Laravel Atomic Locks

Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. For example, Laravel Forge uses atomic locks to ensure that only one remote task is being executed on a server at a time. You may create and manage locks using the Cache::lock method:

if (Cache::lock('foo', 10)->get()) {
    // Lock acquired for 10 seconds...

    Cache::lock('foo')->release();
}

Cache::lock('foo')->get(function () {
    // Lock acquired indefinitely and automatically released...
});

ふー、一日間開けるとあかんわ。
If the lock is not available at the moment you request it, you may instruct Laravel to wait for a specified number of seconds. If the lock can not be acquired within the specified time limit, an Illuminate\Contracts\Cache\LockTimeoutException will be thrown:

The Cache Helper
In addition to using the Cache facade or cache contract, you may also use the global cache function to retrieve and store data via the cache. When the cache function is called with a single, string argument, it will return the value of the given key:

$value = cache('key');
cache(['key' => 'value'], $minutes);

cache(['key' => 'value'], now()->addSeconds(10));

Storing Tagged Cache Items
Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let’s access a tagged cache and put value in the cache:

Cache::tags(['people', 'artists'])->put('John', $john, $minutes);
Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);

Removing Tagged Cache Items
You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either people, authors, or both. So, both Anne and John would be removed from the cache:

Cache::tags([‘people’, ‘authors’])->flush();
In contrast, this statement would remove only caches tagged with authors, so Anne would be removed, but not John:

Cache::tags(‘authors’)->flush();
Adding Custom Cache Drivers
Writing The Driver
To create our custom cache driver, we first need to implement the Illuminate\Contracts\Cache\Store contract. So, a MongoDB cache implementation would look something like this:

namespace App\Extensions;

use Illuminate\Contracts\Cache\Store;

class MongoStore implements Store
{
public function get($key) {}
public function many(array $keys);
public function put($key, $value, $minutes) {}
public function putMany(array $values, $minutes);
public function increment($key, $value = 1) {}
public function decrement($key, $value = 1) {}
public function forever($key, $value) {}
public function forget($key) {}
public function flush() {}
public function getPrefix() {}
}
We just need to implement each of these methods using a MongoDB connection. For an example of how to implement each of these methods, take a look at the Illuminate\Cache\MemcachedStore in the framework source code. Once our implementation is complete, we can finish our custom driver registration.

Cache::extend(‘mongo’, function ($app) {
return Cache::repository(new MongoStore);
});

protected $listen = [
    'Illuminate\Cache\Events\CacheHit' => [
        'App\Listeners\LogCacheHit',
    ],

    'Illuminate\Cache\Events\CacheMissed' => [
        'App\Listeners\LogCacheMissed',
    ],

    'Illuminate\Cache\Events\KeyForgotten' => [
        'App\Listeners\LogKeyForgotten',
    ],

    'Illuminate\Cache\Events\KeyWritten' => [
        'App\Listeners\LogKeyWritten',
    ],
];

Laravel Cache

frameworkが提供するCacheがよーわからん。

Configuration
Laravel provides an expressive, unified API for various caching backends. The cache configuration is located at config/cache.php. In this file you may specify which cache driver you would like to be used by default throughout your application. Laravel supports popular caching backends like Memcached and Redis out of the box.

The cache configuration file also contains various other options, which are documented within the file, so make sure to read over these options. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver.

Driver Prerequisites
Database
When using the database cache driver, you will need to setup a table to contain the cache items. You’ll find an example Schema declaration for the table below:

Schema::create('cache', function ($table) {
    $table->string('key')->unique();
    $table->text('value');
    $table->integer('expiration');
});

Memcached
Using the Memcached driver requires the Memcached PECL package to be installed. You may list all of your Memcached servers in the config/cache.php configuration file:

'memcached' => [
    [
        'host' => '127.0.0.1',
        'port' => 11211,
        'weight' => 100
    ],
],

You may also set the host option to a UNIX socket path. If you do this, the port option should be set to 0:

'memcached' => [
    [
        'host' => '/var/run/memcached/memcached.sock',
        'port' => 0,
        'weight' => 100
    ],
],

Redis
Before using a Redis cache with Laravel, you will need to either install the predis/predis package (~1.0) via Composer or install the PhpRedis PHP extension via PECL.

For more information on configuring Redis, consult its Laravel documentation page.

Obtaining A Cache Instance
The Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository contracts provide access to Laravel’s cache services. The Factory contract provides access to all cache drivers defined for your application. The Repository contract is typically an implementation of the default cache driver for your application as specified by your cache configuration file.

However, you may also use the Cache facade, which is what we will use throughout this documentation. The Cache facade provides convenient, terse access to the underlying implementations of the Laravel cache contracts:

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;

class UserController extends Controller
{
    /**
     * Show a list of all users of the application.
     *
     * @return Response
     */
    public function index()
    {
        $value = Cache::get('key');

        //
    }
}

Accessing Multiple Cache Stores
Using the Cache facade, you may access various cache stores via the store method. The key passed to the store method should correspond to one of the stores listed in the stores configuration array in your cache configuration file:

$value = Cache::store(‘file’)->get(‘foo’);

Cache::store(‘redis’)->put(‘bar’, ‘baz’, 10);

Retrieving Items From The Cache
The get method on the Cache facade is used to retrieve items from the cache. If the item does not exist in the cache, null will be returned. If you wish, you may pass a second argument to the get method specifying the default value you wish to be returned if the item doesn’t exist:

$value = Cache::get(‘key’);

$value = Cache::get(‘key’, ‘default’);
You may even pass a Closure as the default value. The result of the Closure will be returned if the specified item does not exist in the cache. Passing a Closure allows you to defer the retrieval of default values from a database or other external service:

$value = Cache::get(‘key’, function () {
return DB::table(…)->get();
});

Checking For Item Existence
The has method may be used to determine if an item exists in the cache. This method will return false if the value is null or false:

if (Cache::has(‘key’)) {
//
}

Incrementing / Decrementing Values
The increment and decrement methods may be used to adjust the value of integer items in the cache. Both of these methods accept an optional second argument indicating the amount by which to increment or decrement the item’s value:

Cache::increment(‘key’);
Cache::increment(‘key’, $amount);
Cache::decrement(‘key’);
Cache::decrement(‘key’, $amount);
Retrieve & Store
Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn’t exist. For example, you may wish to retrieve all users from the cache or, if they don’t exist, retrieve them from the database and add them to the cache. You may do this using the Cache::remember method:

$value = Cache::remember(‘users’, $minutes, function () {
return DB::table(‘users’)->get();
});
If the item does not exist in the cache, the Closure passed to the remember method will be executed and its result will be placed in the cache.

You may use the rememberForever method to retrieve an item from the cache or store it forever:

$value = Cache::rememberForever(‘users’, function () {
return DB::table(‘users’)->get();
});

Retrieve & Delete
If you need to retrieve an item from the cache and then delete the item, you may use the pull method. Like the get method, null will be returned if the item does not exist in the cache:

$value = Cache::pull(‘key’);

Storing Items In The Cache
You may use the put method on the Cache facade to store items in the cache. When you place an item in the cache, you need to specify the number of minutes for which the value should be cached:

Cache::put(‘key’, ‘value’, $minutes);
Instead of passing the number of minutes as an integer, you may also pass a DateTime instance representing the expiration time of the cached item:

$expiresAt = now()->addMinutes(10);

Cache::put(‘key’, ‘value’, $expiresAt);

Store If Not Present
The add method will only add the item to the cache if it does not already exist in the cache store. The method will return true if the item is actually added to the cache. Otherwise, the method will return false:

Cache::add(‘key’, ‘value’, $minutes);
Storing Items Forever
The forever method may be used to store an item in the cache permanently. Since these items will not expire, they must be manually removed from the cache using the forget method:

Cache::forever(‘key’, ‘value’);
Tip!! If you are using the Memcached driver, items that are stored “forever” may be removed when the cache reaches its size limit.

Removing Items From The Cache
You may remove items from the cache using the forget method:

Cache::forget(‘key’);
You may clear the entire cache using the flush method:

Cache::flush();
Note: Flushing the cache does not respect the cache prefix and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications.

Authorizing Channels

Remember, users must be authorized to listen on private channels. We may define our channel authorization rules in the routes/channels.php file. In this example, we need to verify that any user attempting to listen on the private order.1 channel is actually the creator of the order:

Broadcast::channel('order.{orderId}', function ($user, $orderId) {
    return $user->id === Order::findOrNew($orderId)->user_id;
});

The channel method accepts two arguments: the name of the channel and a callback which returns true or false indicating whether the user is authorized to listen on the channel.

All authorization callbacks receive the currently authenticated user as their first argument and any additional wildcard parameters as their subsequent arguments. In this example, we are using the {orderId} placeholder to indicate that the “ID” portion of the channel name is a wildcard.

Listening For Event Broadcasts
Next, all that remains is to listen for the event in our JavaScript application. We can do this using Laravel Echo. First, we’ll use the private method to subscribe to the private channel. Then, we may use the listen method to listen for the ShippingStatusUpdated event. By default, all of the event’s public properties will be included on the broadcast event:

Echo.private(`order.${orderId}`)
    .listen('ShippingStatusUpdated', (e) => {
        console.log(e.update);
    });

To inform Laravel that a given event should be broadcast, implement the Illuminate\Contracts\Broadcasting\ShouldBroadcast interface on the event class. This interface is already imported into all event classes generated by the framework so you may easily add it to any of your events.

The ShouldBroadcast interface requires you to implement a single method: broadcastOn. The broadcastOn method should return a channel or array of channels that the event should broadcast on. The channels should be instances of Channel, PrivateChannel, or PresenceChannel. Instances of Channel represent public channels that any user may subscribe to, while PrivateChannels and PresenceChannels represent private channels that require channel authorization:

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ServerCreated implements ShouldBroadcast
{
    use SerializesModels;

    public $user;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('user.'.$this->user->id);
    }
}

ほんまや、broadcastonって書いてる。
Then, you only need to fire the event as you normally would. Once the event has been fired, a queued job will automatically broadcast the event over your specified broadcast driver.

Broadcast Name
By default, Laravel will broadcast the event using the event’s class name. However, you may customize the broadcast name by defining a broadcastAs method on the event:
なに、次はbroadcastAs

public function broadcastAs()
{
    return 'server.created';
}

When an event is broadcast, all of its public properties are automatically serialized and broadcast as the event’s payload, allowing you to access any of its public data from your JavaScript application. So, for example, if your event has a single public $user property that contains an Eloquent model, the event’s broadcast payload would be:

{
    "user": {
        "id": 1,
        "name": "Patrick Stewart"
        ...
    }
}
public function broadcastWith()
{
    return ['id' => $this->user->id];
}

Broadcast Queue
By default, each broadcast event is placed on the default queue for the default queue connection specified in your queue.php configuration file. You may customize the queue used by the broadcaster by defining a broadcastQueue property on your event class. This property should specify the name of the queue you wish to use when broadcasting:

use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class ShippingStatusUpdated implements ShouldBroadcastNow
{
    //
}
 Broadca
public function broadcastWhen()
{
    return $this->value > 100;
}

Authorizing Channels
Private channels require you to authorize that the currently authenticated user can actually listen on the channel. This is accomplished by making an HTTP request to your Laravel application with the channel name and allowing your application to determine if the user can listen on that channel. When using Laravel Echo, the HTTP request to authorize subscriptions to private channels will be made automatically; however, you do need to define the proper routes to respond to these requests.

Defining Authorization Routes
Thankfully, Laravel makes it easy to define the routes to respond to channel authorization requests. In the BroadcastServiceProvider included with your Laravel application, you will see a call to the Broadcast::routes method. This method will register the /broadcasting/auth route to handle authorization requests:

roadcast::routes();
The Broadcast::routes method will automatically place its routes within the web middleware group; however, you may pass an array of route attributes to the method if you would like to customize the assigned attributes:

Broadcast::routes($attributes);
あれ、broadcastって別にOauthではないよね。

Defining Authorization Callbacks
Next, we need to define the logic that will actually perform the channel authorization. This is done in the routes/channels.php file that is included with your application. In this file, you may use the Broadcast::channel method to register channel authorization callbacks

Broadcast::channel('order.{orderId}', function ($user, $orderId) {
    return $user->id === Order::findOrNew($orderId)->user_id;
});

書き方がむずいな。
The channel method accepts two arguments: the name of the channel and a callback which returns true or false indicating whether the user is authorized to listen on the channel.

All authorization callbacks receive the currently authenticated user as their first argument and any additional wildcard parameters as their subsequent arguments. In this example, we are using the {orderId} placeholder to indicate that the “ID” portion of the channel name is a wildcard.
これjavaもやんのかーーーーーーーー
Authorization Callback Model Binding
Just like HTTP routes, channel routes may also take advantage of implicit and explicit route model binding. For example, instead of receiving the string or numeric order ID, you may request an actual Order model instance:

use App\Order;

Broadcast::channel('order.{order}', function ($user, Order $order) {
    return $user->id === $order->user_id;
});

Defining Channel Classes
If your application is consuming many different channels, your routes/channels.php file could become bulky. So, instead of using Closures to authorize channels, you may use channel classes. To generate a channel class, use the make:channel Artisan command. This command will place a new channel class in the App/Broadcasting directory.

php artisan make:channel OrderChannel
Next, register your channel in your routes/channels.php file:
use App\Broadcasting\OrderChannel;

Broadcast::channel(‘order.{order}’, OrderChannel::class);

Finally, you may place the authorization logic for your channel in the channel class’ join method. This join method will house the same logic you would have typically placed in your channel authorization Closure. Of course, you may also take advantage of channel model binding:

namespace App\Broadcasting;

use App\User;
use App\Order;

class OrderChannel
{
    /**
     * Create a new channel instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Authenticate the user's access to the channel.
     *
     * @param  \App\User  $user
     * @param  \App\Order  $order
     * @return array|bool
     */
    public function join(User $user, Order $order)
    {
        return $user->id === $order->user_id;
    }
}

Only To Others
When building an application that utilizes event broadcasting, you may substitute the event function with the broadcast function. Like the event function, the broadcast function dispatches the event to your server-side listeners:

broadcast(new ShippingStatusUpdated($update));
However, the broadcast function also exposes the toOthers method which allows you to exclude the current user from the broadcast’s recipients:

broadcast(new ShippingStatusUpdated($update))->toOthers();
To better understand when you may want to use the toOthers method, let’s imagine a task list application where a user may create a new task by entering a task name. To create a task, your application might make a request to a /task end-point which broadcasts the task’s creation and returns a JSON representation of the new task. When your JavaScript application receives the response from the end-point, it might directly insert the new task into its task list like so:

axios.post(‘/task’, task)
.then((response) => {
this.tasks.push(response.data);
});
However, remember that we also broadcast the task’s creation. If your JavaScript application is listening for this event in order to add tasks to the task list, you will have duplicate tasks in your list: one from the end-point and one from the broadcast. You may solve this by using the toOthers method to instruct the broadcaster to not broadcast the event to the current user.

Note: Your event must use the Illuminate\Broadcasting\InteractsWithSockets trait in order to call the toOthers method.

Configuration
When you initialize a Laravel Echo instance, a socket ID is assigned to the connection. If you are using Vue and Axios, the socket ID will automatically be attached to every outgoing request as a X-Socket-ID header. Then, when you call the toOthers method, Laravel will extract the socket ID from the header and instruct the broadcaster to not broadcast to any connections with that socket ID.

If you are not using Vue and Axios, you will need to manually configure your JavaScript application to send the X-Socket-ID header. You may retrieve the socket ID using the Echo.socketId method:

var socketId = Echo.socketId();
そもそもこれって、jsとの通信だけど、どっち側が考えてなかった。laravelのdemo作らんと。

Installing Laravel Echo
Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel. You may install Echo via the NPM package manager. In this example, we will also install the pusher-js package since we will be using the Pusher broadcaster:

npm install –save laravel-echo pusher-js
Once Echo is installed, you are ready to create a fresh Echo instance in your application’s JavaScript. A great place to do this is at the bottom of the resources/js/bootstrap.js file that is included with the Laravel framework:
pusher.jsってなんか笑えるな。

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key'
});
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
    cluster: 'eu',
    encrypted: true
});

Using An Existing Client Instance
If you already have a Pusher or Socket.io client instance that you would like Echo to utilize, you may pass it to Echo via the client configuration option:

const client = require(‘pusher-js’);

window.Echo = new Echo({
broadcaster: ‘pusher’,
key: ‘your-pusher-key’,
client: client
});

Notifications
By pairing event broadcasting with notifications, your JavaScript application may receive new notifications as they occur without needing to refresh the page. First, be sure to read over the documentation on using the broadcast notification channel.

Once you have configured a notification to use the broadcast channel, you may listen for the broadcast events using Echo’s notification method. Remember, the channel name should match the class name of the entity receiving the notifications:

Echo.private(`App.User.${userId}`)
.notification((notification) => {
console.log(notification.type);
});
In this example, all notifications sent to App\User instances via the broadcast channel would be received by the callback. A channel authorization callback for the App.User.{id} channel is included in the default BroadcastServiceProvider that ships with the Laravel framework.

Laravel broadcasting

broadcastingって、テレビなどでよく使う単語だけど、laravelだと、viewをbroadcastingっていみ? 

In many modern web applications, WebSockets are used to implement realtime, live-updating user interfaces. When some data is updated on the server, a message is typically sent over a WebSocket connection to be handled by the client. This provides a more robust, efficient alternative to continually polling your application for changes.

To assist you in building these types of applications, Laravel makes it easy to “broadcast” your events over a WebSocket connection. Broadcasting your Laravel events allows you to share the same event names between your server-side code and your client-side JavaScript application.
web socketといえばsocket ioか。サーバーサイドとjsでconnectionか。broadcastingって意外と面白いやんけ。

Before diving into event broadcasting, make sure you have read all of the documentation regarding Laravel events and listeners.
なんだよ、このtips。みんなドキュメント読めって言ってくる。なんか、できるエンジニアって、ドキュメント読め、ってよく言う気がするんだが、何故だろう。

All of your application’s event broadcasting configuration is stored in the config/broadcasting.php configuration file. Laravel supports several broadcast drivers out of the box: Pusher, Redis, and a log driver for local development and debugging. Additionally, a null driver is included which allows you to totally disable broadcasting. A configuration example is included for each of these drivers in the config/broadcasting.php configuration file.
とりあえずソースコードを見ます。minifyされてないところがいいね。当たり前か。

Broadcast Service Provider
Before broadcasting any events, you will first need to register the App\Providers\BroadcastServiceProvider. In fresh Laravel applications, you only need to uncomment this provider in the providers array of your config/app.php configuration file. This provider will allow you to register the broadcast authorization routes and callbacks.

CSRF Token
Laravel Echo will need access to the current session’s CSRF token. You should verify that your application’s head HTML element defines a meta tag containing the CSRF token:

<meta name="csrf-token" content="{{ csrf_token() }}">

web socketってcsrf必要だっけ?

Driver Prerequisites
Pusher
If you are broadcasting your events over Pusher, you should install the Pusher PHP SDK using the Composer package manager:

Next, you should configure your Pusher credentials in the config/broadcasting.php configuration file. An example Pusher configuration is already included in this file, allowing you to quickly specify your Pusher key, secret, and application ID. The config/broadcasting.php file’s pusher configuration also allows you to specify additional options that are supported by Pusher, such as the cluster:

‘options’ => [
‘cluster’ => ‘eu’,
‘encrypted’ => true
],
When using Pusher and Laravel Echo, you should specify pusher as your desired broadcaster when instantiating the Echo instance in your resources/js/bootstrap.js file:

import Echo from "laravel-echo"

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key'
});

pusherなんてあるんだ。
Redisか、インメモリデータベース。redisでサービス作らないと、表層的な理解しかできん。

If you are using the Redis broadcaster, you should install the Predis library:

composer require predis/predis
The Redis broadcaster will broadcast messages using Redis’ pub / sub feature; however, you will need to pair this with a WebSocket server that can receive the messages from Redis and broadcast them to your WebSocket channels.

When the Redis broadcaster publishes an event, it will be published on the event’s specified channel names and the payload will be a JSON encoded string containing the event name, a data payload, and the user that generated the event’s socket ID (if applicable).

Socket.IO
If you are going to pair the Redis broadcaster with a Socket.IO server, you will need to include the Socket.IO JavaScript client library in your application. You may install it via the NPM package manager:

npm install –save socket.io-client
Next, you will need to instantiate Echo with the socket.io connector and a host.
やっぱりsocket io

import Echo from "laravel-echo"

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

Finally, you will need to run a compatible Socket.IO server. Laravel does not include a Socket.IO server implementation; however, a community driven Socket.IO server is currently maintained at the tlaverdure/laravel-echo-server GitHub repository.

Queue Prerequisites
Before broadcasting events, you will also need to configure and run a queue listener. All event broadcasting is done via queued jobs so that the response time of your application is not seriously affected.

Laravel Defining Input Expectations

When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the signature property on your commands. The signature property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax.

Arguments
All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one required argument: user:
なんじゃこりゃ。

protected $signature = 'email:send {user}';

You may also make arguments optional and define default values for arguments:

email:send {user?}

// Optional argument with default value...
email:send {user=foo}

Options
Options, like arguments, are another form of user input. Options are prefixed by two hyphens (–) when they are specified on the command line. There are two types of options: those that receive a value and those that don’t. Options that don’t receive a value serve as a boolean “switch”. Let’s take a look at an example of this type of option:
optionは–と書きます。

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user} {--queue}';

In this example, the –queue switch may be specified when calling the Artisan command. If the –queue switch is passed, the value of the option will be true. Otherwise, the value will be false:

php artisan email:send 1 –queue

Options With Values
Next, let’s take a look at an option that expects a value. If the user must specify a value for an option, suffix the option name with a = sign:

protected $signature = 'email:send {user} {--queue=}';

In this example, the user may pass a value for the option like so:

php artisan email:send 1 –queue=default
You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used:

email:send {user} {–queue=default}
なんじゃこりゃ、email:sendってメール送付?

Option Shortcuts
To assign a shortcut when defining an option, you may specify it before the option name and use a | delimiter to separate the shortcut from the full option name:
email:send {user} {–Q|queue}

Input Arrays
If you would like to define arguments or options to expect array inputs, you may use the * character. First, let’s take a look at an example that specifies an array argument:

email:send {user*}
When calling this method, the user arguments may be passed in order to the command line. For example, the following command will set the value of user to [‘foo’, ‘bar’]:

php artisan email:send foo bar
When defining an option that expects an array input, each option value passed to the command should be prefixed with the option name:

email:send {user} {–id=*}

php artisan email:send –id=1 –id=2
ワイルドカードとオプション。オプションの使い勝手が良い。

Input Descriptions
You may assign descriptions to input arguments and options by separating the parameter from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines:

protected $signature = 'email:send
                        {user : The ID of the user}
                        {--queue= : Whether the job should be queued}';

コメントみたいだけど、使い勝手は良さそう。わざわざやらんか。

Retrieving Input
While your command is executing, you will obviously need to access the values for the arguments and options accepted by your command. To do so, you may use the argument and option methods:

public function handle()
{
    $userId = $this->argument('user');

    //
}

Retrievingは取得って意味。mysqlのfetchばっかり使っていたが、retrievingにも慣れないと。。

$arguments = $this->arguments();
optionもretrievigか。

// Retrieve a specific option...
$queueName = $this->option('queue');

// Retrieve all options...
$options = $this->options();

If the argument or option does not exist, null will be returned.

Prompting For Input
In addition to displaying output, you may also ask the user to provide input during the execution of your command. The ask method will prompt the user with the given question, accept their input, and then return the user’s input back to your command:

The secret method is similar to ask, but the user’s input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as a password:

$password = $this->secret(‘What is the password?’);
Asking For Confirmation
If you need to ask the user for a simple confirmation, you may use the confirm method. By default, this method will return false. However, if the user enters y or yes in response to the prompt, the method will return true.

Auto-Completion
The anticipate method can be used to provide auto-completion for possible choices. The user can still choose any answer, regardless of the auto-completion hints:

$name = $this->anticipate(‘What is your name?’, [‘Taylor’, ‘Dayle’]);
Multiple Choice Questions
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:
$name = $this->choice(‘What is your name?’, [‘Taylor’, ‘Dayle’], $defaultIndex);

Writing Output
To send output to the console, use the line, info, comment, question and error methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let’s display some general information to the user. Typically, the info method will display in the console as green text:
これは実践でやらんとわからんわ。

public function handle()
{
    $this->info('Display this on the screen');
}
$this->error('Something went wrong!');
$this->line('Display this on the screen');

Table Layouts
The table method makes it easy to correctly format multiple rows / columns of data. Just pass in the headers and rows to the method. The width and height will be dynamically calculated based on the given data:

$headers = ['Name', 'Email'];
$users = App\User::all(['name', 'email'])->toArray();
$this->table($headers, $users);

Progress Bars
For long running tasks, it could be helpful to show a progress indicator. Using the output object, we can start, advance and stop the Progress Bar. First, define the total number of steps the process will iterate through. Then, advance the Progress Bar after processing each item:
progress barsはjsかcssだろ。

$users = App\User::all();

$bar = $this->output->createProgressBar(count($users));

foreach ($users as $user) {
    $this->performTask($user);

    $bar->advance();
}

$bar->finish();

performTask($user);とprogressbarが上手くリンクせんな。

Registering Commands
Because of the load method call in your console kernel’s commands method, all commands within the app/Console/Commands directory will automatically be registered with Artisan. In fact, you are free to make additional calls to the load method to scan other directories for Artisan commands:

protected function commands()
{
$this->load(__DIR__.’/Commands’);
$this->load(__DIR__.’/MoreCommands’);

// …
}

Programmatically Executing Commands
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:

Route::get('/foo', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});

Artisan::call(’email:send’ これはなんだ?controllerの中でartisanって書けるの?コマンドラインだけではないのか。。

Using the queue method on the Artisan facade, you may even queue Artisan commands so they are processed in the background by your queue workers. Before using this method, make sure you have configured your queue and are running a queue listener:
queuesをcallのところで使用している。

Route::get('/foo', function () {
    Artisan::queue('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});
Artisan::queue('email:send', [
    'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');

Laravel Artisan Console

ついにDigging Deeperまできました。特に興味があるのは、Cache, mail, filestrage
broadcasting, collection, queuesは意味がわからん。他は重要度が不明。
まずArtisanから。

Introduction
Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application. To view a list of all available Artisan commands, you may use the list command:

php artisan list
Available commands:
clear-compiled Remove the compiled class file
down Put the application into maintenance mode
dump-server Start the dump server to collect dump information.
env Display the current framework environment
help Displays help for a command
inspire Display an inspiring quote
list Lists commands
migrate Run the database migrations
optimize Cache the framework bootstrap files
preset Swap the front-end scaffolding for the application
serve Serve the application on the PHP development server
tinker Interact with your application
up Bring the application out of maintenance mode
app
app:name Set the application namespace
auth
auth:clear-resets Flush expired password reset tokens
cache
cache:clear Flush the application cache
cache:forget Remove an item from the cache
cache:table Create a migration for the cache database table
config
config:cache Create a cache file for faster configuration loading
config:clear Remove the configuration cache file
db
db:seed Seed the database with records
event
event:generate Generate the missing events and listeners based on registration
key
key:generate Set the application key
make
make:auth Scaffold basic login and registration views and routes
make:channel Create a new channel class
make:command Create a new Artisan command
make:controller Create a new controller class
make:event Create a new event class
make:exception Create a new custom exception class
make:factory Create a new model factory
make:job Create a new job class
make:listener Create a new event listener class
make:mail Create a new email class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:notification Create a new notification class
make:observer Create a new observer class
make:policy Create a new policy class
make:provider Create a new service provider class
make:request Create a new form request class
make:resource Create a new resource
make:rule Create a new validation rule
make:seeder Create a new seeder class
make:test Create a new test class
migrate
migrate:fresh Drop all tables and re-run all migrations
migrate:install Create the migration repository
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
migrate:status Show the status of each migration
notifications
notifications:table Create a migration for the notifications table
optimize
optimize:clear Remove the cached bootstrap files
package
package:discover Rebuild the cached package manifest
queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:restart Restart queue worker daemons after their current job
queue:retry Retry a failed queue job
queue:table Create a migration for the queue jobs database table
queue:work Start processing jobs on the queue as a daemon
route
route:cache Create a route cache file for faster route registration
route:clear Remove the route cache file
route:list List all registered routes
schedule
schedule:finish Handle the completion of a scheduled command
schedule:run Run the scheduled commands
session
session:table Create a migration for the session database table
storage
storage:link Create a symbolic link from “public/storage” to “storage/app/public”
vendor
vendor:publish Publish any publishable assets from vendor packages
view
view:cache Compile all of the application’s Blade templates
view:clear Clear all compiled view files
makeが多いのと、意外とqueueがあるな。
php artisan help migrate

Laravel REPL
All Laravel applications include Tinker, a REPL powered by the PsySH package. Tinker allows you to interact with your entire Laravel application on the command line, including the Eloquent ORM, jobs, events, and more. To enter the Tinker environment, run the tinker Artisan command:
php artisan tinker

In addition to the commands provided with Artisan, you may also build your own custom commands. Commands are typically stored in the app/Console/Commands directory; however, you are free to choose your own storage location as long as your commands can be loaded by Composer.
ここまでいったらすげーわ。

Generating Commands
To create a new command, use the make:command Artisan command. This command will create a new command class in the app/Console/Commands directory. Don’t worry if this directory does not exist in your application, since it will be created the first time you run the make:command Artisan command. The generated command will include the default set of properties and methods that are present on all commands:
php artisan make:command SendEmails

After generating your command, you should fill in the signature and description properties of the class, which will be used when displaying your command on the list screen. The handle method will be called when your command is executed. You may place your command logic in this method.

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.

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 will automatically inject all dependencies type-hinted in the constructor or handle method:

namespace App\Console\Commands;

use App\User;
use App\DripEmailer;
use Illuminate\Console\Command;

class SendEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'email:send {user}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send drip e-mails to a user';

    /**
     * The drip e-mail service.
     *
     * @var DripEmailer
     */
    protected $drip;

    /**
     * Create a new command instance.
     *
     * @param  DripEmailer  $drip
     * @return void
     */
    public function __construct(DripEmailer $drip)
    {
        parent::__construct();

        $this->drip = $drip;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->drip->send(User::find($this->argument('user')));
    }
}

parent::__construct();の書き方はわからんぞ。

Closure Commands
Closure based commands provide an alternative to defining console commands as classes. In the same way that route Closures are an alternative to controllers, think of command Closures as an alternative to command classes. Within the commands method of your app/Console/Kernel.php file, Laravel loads the routes/console.php file:

protected function commands()
{
    require base_path('routes/console.php');
}

closureではなく、base_pathを定義します。

Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. Within this file, you may define all of your Closure based routes using the Artisan::command method. The command method accepts two arguments: the command signature and a Closure which receives the commands arguments and options:

rtisan::command('build {project}', function ($project) {
    $this->info("Building {$project}!");
});

Type-Hinting Dependencies
In addition to receiving your command’s arguments and options, command Closures may also type-hint additional dependencies that you would like resolved out of the service container:

use App\User;
use App\DripEmailer;

Artisan::command(’email:send {user}’, function (DripEmailer $drip, $user) {
$drip->send(User::find($user));
});
Closure Command Descriptions
When defining a Closure based command, you may use the describe method to add a description to the command. This description will be displayed when you run the php artisan list or php artisan help commands:

Artisan::command(‘build {project}’, function ($project) {
$this->info(“Building {$project}!”);
})->describe(‘Build the project’);]
うおーなんか疲れたーーーーーーー

Laravel Resetting Passwords

resetって、単にpasswordをupdateすればいいだけじゃないのか?

Want to get started fast? Just run php artisan make:auth in a fresh Laravel application and navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. This single command will take care of scaffolding your entire authentication system, including resetting passwords!

Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this on each application, Laravel provides convenient methods for sending password reminders and performing password resets.
確かにパスワード忘れることってよくあります。

Database Considerations
To get started, verify that your App\User model implements the Illuminate\Contracts\Auth\CanResetPassword contract. Of course, the App\User model included with the framework already implements this interface, and uses the Illuminate\Auth\Passwords\CanResetPassword trait to include the methods needed to implement the interface.

Generating The Reset Token Table Migration
Next, a table must be created to store the password reset tokens. The migration for this table is included with Laravel out of the box, and resides in the database/migrations directory. So, all you need to do is run your database migrations:
php artisan migrate
migrationってことあるごとにするんだ。tableを作成する度か。

Routing
Laravel includes Auth\ForgotPasswordController and Auth\ResetPasswordController classes that contains the logic necessary to e-mail password reset links and reset user passwords. All of the routes needed to perform password resets may be generated using the make:auth Artisan command:
php artisan make:auth
あれ、make:authは最初にログイン機能を実装する時だったはず。

Views
Again, Laravel will generate all of the necessary views for password reset when the make:auth command is executed. These views are placed in resources/views/auth/passwords. You are free to customize them as needed for your application.

After Resetting Passwords
Once you have defined the routes and views to reset your user’s passwords, you may access the route in your browser at /password/reset. The ForgotPasswordController included with the framework already includes the logic to send the password reset link e-mails, while the ResetPasswordController includes the logic to reset user passwords.

After a password is reset, the user will automatically be logged into the application and redirected to /home. You can customize the post password reset redirect location by defining a redirectTo property on the ResetPasswordController:

protected $redirectTo = ‘/dashboard’;
ああ、なるほど、reset用のviewをartisanで一発で作れるって意味か。すげー。

Customization
Authentication Guard Customization
In your auth.php configuration file, you may configure multiple “guards”, which may be used to define authentication behavior for multiple user tables. You can customize the included ResetPasswordController to use the guard of your choice by overriding the guard method on the controller. This method should return a guard instance:

use Illuminate\Support\Facades\Auth;

protected function guard()
{
    return Auth::guard('guard-name');
}

Password Broker Customization
In your auth.php configuration file, you may configure multiple password “brokers”, which may be used to reset passwords on multiple user tables. You can customize the included ForgotPasswordController and ResetPasswordController to use the broker of your choice by overriding the broker method:

use Illuminate\Support\Facades\Password;

/**
 * Get the broker to be used during password reset.
 *
 * @return PasswordBroker
 */
protected function broker()
{
    return Password::broker('name');
}