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');
}

Laravel Hashing

「ハッシュ化」とは、「元データ」をハッシュアルゴリズム(md5、sha1、sha2等)に従って、固定長のランダムに見える値に「不可逆変換」する行為
Google検索もデータをhash化してるんじゃなかったっけ。

Introduction
The Laravel Hash facade provides secure Bcrypt and Argon2 hashing for storing user passwords. If you are using the built-in LoginController and RegisterController classes that are included with your Laravel application, they will use Bcrypt for registration and authentication by default.

Tip!! Bcrypt is a great choice for hashing passwords because its “work factor” is adjustable, which means that the time it takes to generate a hash can be increased as hardware power increases.

Bcrypt、Argon2? パスワード保存に使うアルゴリズム。なるほど。
Argon2は2015年7月に開催されたパスワードハッシュ競技会(英語版)で優勝した鍵導出関数
なるほどー、面白いね、この分野。

Basic Usage
You may hash a password by calling the make method on the Hash facade:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;

class UpdatePasswordController extends Controller
{
    /**
     * Update the password for the user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        // Validate the new password length...

        $request->user()->fill([
            'password' => Hash::make($request->newPassword)
        ])->save();
    }
}

Hash::make($request->newPassword)って、ナニコレ。passwordをhash化してるってこと?
確かにDBにはハッシュ化された値です。

Adjusting The Bcrypt Work Factor
If you are using the Bcrypt algorithm, the make method allows you to manage the work factor of the algorithm using the rounds option; however, the default is acceptable for most applications:

$hashed = Hash::make('password', [
    'rounds' => 12
]);

ぬお、覚えること多すぎる。
Adjusting The Argon2 Work Factor
If you are using the Argon2 algorithm, the make method allows you to manage the work factor of the algorithm using the memory, time, and threads options; however, the defaults are acceptable for most applications:

$hashed = Hash::make('password', [
    'memory' => 1024,
    'time' => 2,
    'threads' => 2,
]);

ハッシュ化のアルゴリズム、チューニングできるんか。おもろ。

Verifying A Password Against A Hash
The check method allows you to verify that a given plain-text string corresponds to a given hash. However, if you are using the LoginController included with Laravel, you will probably not need to use this directly, as this controller automatically calls this method:

if (Hash::check('plain-text', $hashedPassword)) {
    // The passwords match...
}

Checking If A Password Needs To Be Rehashed
The needsRehash function allows you to determine if the work factor used by the hasher has changed since the password was hashed:

if (Hash::needsRehash($hashed)) {
    $hashed = Hash::make('plain-text');
}

Laravel Encryption

しかしdocumentの量多いな
これlaravel開発者が作ってるんだろうか。まあ、関わってることは確かだな。そう思うとテンションがあがります。

Introduction
Laravel’s encrypter uses OpenSSL to provide AES-256 and AES-128 encryption. You are strongly encouraged to use Laravel’s built-in encryption facilities and not attempt to roll your own “home grown” encryption algorithms. All of Laravel’s encrypted values are signed using a message authentication code (MAC) so that their underlying value can not be modified once encrypted.
AES-256:AES(Advanced Encryption Standard)と呼ばれる暗号化方式のうち、256ビット長の暗号鍵を使用する方式
AES-128:Advanced Encryption Standard (AES) は、DESに代わる新しい標準暗号となる共通鍵暗号アルゴリズム

暗号化は少し勉強したけど、この分野、奥がすげー深いからな。片足踏み入れると抜け出せなくなる。

Configuration
Before using Laravel’s encrypter, you must set a key option in your config/app.php configuration file. You should use the php artisan key:generate command to generate this key since this Artisan command will use PHP’s secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure.
linuxの公開鍵、秘密鍵の仕組みと似てる。

Using The Encrypter
Encrypting A Value
You may encrypt a value using the encrypt helper. All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string:

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Store a secret message for the user.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function storeSecret(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $user->fill([
            'secret' => encrypt($request->secret)
        ])->save();
    }
}

encrypt($request->secret)って関数があるから、encryptって作ってるんだろうな。凄い。

Encrypting Without Serialization
Encrypted values are passed through serialize during encryption, which allows for encryption of objects and arrays. Thus, non-PHP clients receiving encrypted values will need to unserialize the data. If you would like to encrypt and decrypt values without serialization, you may use the encryptString and decryptString methods of the Crypt facade:

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');
$decrypted = Crypt::decryptString($encrypted);

encryptとdecrptってなんだっけ。これ、encode, decodeみたいなもん?

Decrypting A Value
You may decrypt values using the decrypt helper. If the value can not be properly decrypted, such as when the MAC is invalid, an Illuminate\Contracts\Encryption\DecryptException will be thrown:

use Illuminate\Contracts\Encryption\DecryptException;

try {
    $decrypted = decrypt($encryptedValue);
} catch (DecryptException $e) {
    //
}

暗号化って、アプリケーションの中でどう使うかですな。
セキュアな通信に使いたいのはわかるが、アプリケーション内でdecrypt, cryptするイメージが湧かない。

Laravel Email Verification

Introduction
Many web applications require users to verify their email addresses before using the application. Rather than forcing you to re-implement this on each application, Laravel provides convenient methods for sending and verifying email verification requests.
Email Verificationって、メールアドレスかどうかの判定ってこと?不正メールか、スパムメールかなども含まれるのか?でもSMTPだけだから、アドレス判定だけだろうか。

To get started, verify that your App\User model implements the Illuminate\Contracts\Auth\MustVerifyEmail contract:

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    // ...
}

MustVerifyEmail って、verify必須に見える。

The Email Verification Column
Next, your user table must contain an email_verified_at column to store the date and time that the email address was verified. By default, the users table migration included with the Laravel framework already includes this column. So, all you need to do is run your database migrations:
email_verified_at column って、単にemailのカラムじゃあかんの?
php artisan migrate

Routing
Laravel includes the Auth\VerificationController class that contains the necessary logic to send verification links and verify emails. To register the necessary routes for this controller, pass the verify option to the Auth::routes method:
Auth::routes([‘verify’ => true]);
説明がえらい雑だな。

Protecting Routes
Route middleware can be used to only allow verified users to access a given route. Laravel ships with a verified middleware, which is defined at Illuminate\Auth\Middleware\EnsureEmailIsVerified. Since this middleware is already registered in your application’s HTTP kernel, all you need to do is attach the middleware to a route definition:

Route::get('profile', function () {
    // Only verified users may enter...
})->middleware('verified');

Views
Laravel will generate all of the necessary email verification views when the make:auth command is executed. This view is placed in resources/views/auth/verify.blade.php. You are free to customize this view as needed for your application.

After Verifying Emails
After an email address is verified, the user will automatically be redirected to /home. You can customize the post verification redirect location by defining a redirectTo method or property on the VerificationController:

protected $redirectTo = ‘/dashboard’;
redirectはroutingのredirectと全く同じ

Events
Laravel dispatches events during the email verification process. You may attach listeners to these events in your EventServiceProvider:

protected $listen = [
    'Illuminate\Auth\Events\Verified' => [
        'App\Listeners\LogVerifiedUser',
    ],
];

email varifyは割と簡単・シンプルのようです。

Laravel Authorization

Introduction
In addition to providing authentication services out of the box, Laravel also provides a simple way to authorize user actions against a given resource. Like authentication, Laravel’s approach to authorization is simple, and there are two primary ways of authorizing actions: gates and policies.

Think of gates and policies like routes and controllers. Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource. We’ll explore gates first and then examine policies.

You do not need to choose between exclusively using gates or exclusively using policies when building an application. Most applications will most likely contain a mixture of gates and policies, and that is perfectly fine! Gates are most applicable to actions which are not related to any model or resource, such as viewing an administrator dashboard. In contrast, policies should be used when you wish to authorize an action for a particular model or resource.

Gates
Writing Gates
Gates are Closures that determine if a user is authorized to perform a given action and are typically defined in the App\Providers\AuthServiceProvider class using the Gate facade. Gates always receive a user instance as their first argument, and may optionally receive additional arguments such as a relevant Eloquent model:

public function boot()
{
    $this->registerPolicies();

    Gate::define('update-post', function ($user, $post) {
        return $user->id == $post->user_id;
    });
}

Gates may also be defined using a Class@method style callback string, like controllers:

Resource Gates
You may also define multiple Gate abilities at once using the resource method:

Gate::resource(‘posts’, ‘App\Policies\PostPolicy’);
This is identical to manually defining the following Gate definitions:

Gate::define('posts.view', 'App\Policies\PostPolicy@view');
Gate::define('posts.create', 'App\Policies\PostPolicy@create');
Gate::define('posts.update', 'App\Policies\PostPolicy@update');
Gate::define('posts.delete', 'App\Policies\PostPolicy@delete');

By default, the view, create, update, and delete abilities will be defined. You may override the default abilities by passing an array as a third argument to the resource method. The keys of the array define the names of the abilities while the values define the method names. For example, the following code will only create two new Gate definitions – posts.image and posts.photo:

Gate::resource('posts', 'PostPolicy', [
    'image' => 'updateImage',
    'photo' => 'updatePhoto',
]);

Authorizing Actions
To authorize an action using gates, you should use the allows or denies methods. Note that you are not required to pass the currently authenticated user to these methods. Laravel will automatically take care of passing the user into the gate Closure:

if (Gate::allows('update-post', $post)) {
    // The current user can update the post...
}

if (Gate::denies('update-post', $post)) {
    // The current user can't update the post...
}
if (Gate::forUser($user)->allows('update-post', $post)) {
    // The user can update the post...
}

if (Gate::forUser($user)->denies('update-post', $post)) {
    // The user can't update the post...
}

Intercepting Gate Checks
Sometimes, you may wish to grant all abilities to a specific user. You may use the before method to define a callback that is run before all other authorization checks:

Gate::before(function ($user, $ability) {
if ($user->isSuperAdmin()) {
return true;
}
});
If the before callback returns a non-null result that result will be considered the result of the check.

You may use the after method to define a callback to be executed after every authorization check. However, you may not modify the result of the authorization check from an after callback:

Gate::after(function ($user, $ability, $result, $arguments) {
    //
});

Creating Policies
Generating Policies
Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.

You may generate a policy using the make:policy artisan command. The generated policy will be placed in the app/Policies directory. If this directory does not exist in your application, Laravel will create it for you:

php artisan make:policy PostPolicy
The make:policy command will generate an empty policy class. If you would like to generate a class with the basic “CRUD” policy methods already included in the class, you may specify a –model when executing the command:

php artisan make:policy PostPolicy –model=Post
Tip!! All policies are resolved via the Laravel service container, allowing you to type-hint any needed dependencies in the policy’s constructor to have them automatically injected.
artisanのコメントがわからんな。

Registering Policies
Once the policy exists, it needs to be registered. The AuthServiceProvider included with fresh Laravel applications contains a policies property which maps your Eloquent models to their corresponding policies. Registering a policy will instruct Laravel which policy to utilize when authorizing actions against a given model:

use App\Post;
use App\Policies\PostPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

policyでPost::class を PostPolicy::class にしてるってこと。Postは元からあるやつちゃんうか。
Writing Policies
Policy Methods
Once the policy has been registered, you may add methods for each action it authorizes. For example, let’s define an update method on our PostPolicy which determines if a given User can update a given Post instance.

The update method will receive a User and a Post instance as its arguments, and should return true or false indicating whether the user is authorized to update the given Post. So, for this example, let’s verify that the user’s id matches the user_id on the post:
なんか、blogベースで話が進んでいるが、updateはデータベースのupdateって意味でOK?

namespace App\Policies;

use App\User;
use App\Post;

class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

updateはfunctionのupdateだ。

You may continue to define additional methods on the policy as needed for the various actions it authorizes. For example, you might define view or delete methods to authorize various Post actions, but remember you are free to give your policy methods any name you like.

Tip!! If you used the –model option when generating your policy via the Artisan console, it will already contain methods for the view, create, update, delete, restore, and forceDelete actions.
mysqlにviewなんてコマンドなかったはず。なんか眠くなってきたぞ。

Methods Without Models
Some policy methods only receive the currently authenticated user and not an instance of the model they authorize. This situation is most common when authorizing create actions. For example, if you are creating a blog, you may wish to check if a user is authorized to create any posts at all.

When defining policy methods that will not receive a model instance, such as a create method, it will not receive a model instance. Instead, you should define the method as only expecting the authenticated user:
modelなしのmethodって、そんなん可能なんかい。

Guest Users
By default, all gates and policies automatically return false if the incoming HTTP request was not initiated by an authenticated user. However, you may allow these authorization checks to pass through to your gates and policies by declaring an “optional” type-hint or supplying a null default value for the user argument definition:
guestユーザーってどういうこと。artisan:authしてるのに?オプションでできるってことか。

namespace App\Policies;

use App\User;
use App\Post;

class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(?User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

Policy Filters
For certain users, you may wish to authorize all actions within a given policy. To accomplish this, define a before method on the policy. The before method will be executed before any other methods on the policy, giving you an opportunity to authorize the action before the intended policy method is actually called. This feature is most commonly used for authorizing application administrators to perform any action:

public function before($user, $ability)
{
    if ($user->isSuperAdmin()) {
        return true;
    }
}

superAdminか確認してるのはわかるが、superAdminってlaravelデフォルトのロール?

If you would like to deny all authorizations for a user you should return false from the before method. If null is returned, the authorization will fall through to the policy method.
相変わらず機能多いなー

Authorizing Actions Using Policies
Via The User Model
The User model that is included with your Laravel application includes two helpful methods for authorizing actions: can and cant. The can method receives the action you wish to authorize and the relevant model. For example, let’s determine if a user is authorized to update a given Post model:
policyを使ってauthorize ってことはpolicy重要じゃん。流してた。

if ($user->can('update', $post)) {
    //
}

can, cantはシンプルだなー

If a policy is registered for the given model, the can method will automatically call the appropriate policy and return the boolean result. If no policy is registered for the model, the can method will attempt to call the Closure based Gate matching the given action name.

Actions That Don’t Require Models
Remember, some actions like create may not require a model instance. In these situations, you may pass a class name to the can method. The class name will be used to determine which policy to use when authorizing the action:

use App\Post;

if ($user->can('create', Post::class)) {
    // Executes the "create" method on the relevant policy...
}

modelを使わない意味がわからん。

Via Middleware
Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers. By default, the Illuminate\Auth\Middleware\Authorize middleware is assigned the can key in your App\Http\Kernel class. Let’s explore an example of using the can middleware to authorize that a user can update a blog post:

use App\Post;

Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');

In this example, we’re passing the can middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method. In this case, since we are using implicit model binding, a Post model will be passed to the policy method. If the user is not authorized to perform the given action, a HTTP response with a 403 status code will be generated by the middleware.
Routeの後にmiddleware(‘can:update,post’);としてます。

Actions That Don’t Require Models
Again, some actions like create may not require a model instance. In these situations, you may pass a class name to the middleware. The class name will be used to determine which policy to use when authorizing the action:

Route::post(‘/post’, function () {
// The current user may create posts…
})->middleware(‘can:create,App\Post’);

Via Controller Helpers
In addition to helpful methods provided to the User model, Laravel provides a helpful authorize method to any of your controllers which extend the App\Http\Controllers\Controller base class. Like the can method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, the authorize method will throw an Illuminate\Auth\Access\AuthorizationException, which the default Laravel exception handler will convert to an HTTP response with a 403 status code:
403はページがない時だったような。

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    /**
     * Update the given blog post.
     *
     * @param  Request  $request
     * @param  Post  $post
     * @return Response
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);

        // The current user can update the blog post...
    }
}

感覚的には理解できるが、わかってない。
Actions That Don’t Require Models
As previously discussed, some actions like create may not require a model instance. In these situations, you may pass a class name to the authorize method. The class name will be used to determine which policy to use when authorizing the action:

public function create(Request $request)
{
    $this->authorize('create', Post::class);

    // The current user can create blog posts...
}

Via Blade Templates
When writing Blade templates, you may wish to display a portion of the page only if the user is authorized to perform a given action. For example, you may wish to show an update form for a blog post only if the user can actually update the post. In this situation, you may use the @can and @cannot family of directives:
bladeでも基本は一緒か。

@can('update', $post)
    <!-- The Current User Can Update The Post -->
@elsecan('create', App\Post::class)
    <!-- The Current User Can Create New Post -->
@endcan

@cannot('update', $post)
    <!-- The Current User Can't Update The Post -->
@elsecannot('create', App\Post::class)
    <!-- The Current User Can't Create New Post -->
@endcannot

Actions That Don’t Require Models
Like most of the other authorization methods, you may pass a class name to the @can and @cannot directives if the action does not require a model instance:

@can(‘create’, App\Post::class)

@endcan

@cannot(‘create’, App\Post::class)

@endcannot
なんか、コードの中にcan, cannotを書くのって、変な気分だなーー、他の言語で見かけないからかな。