Laravel API Authentication (Passport)

Introduction
Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp.
Laravel OAuth2か。また勉強すべきトピックスが増えた。
This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general terminology and features of OAuth2 before continuing

To get started, install Passport via the Composer package manager:

composer require laravel/passport

composerから始めるのか。というか、composerはlaravel/laravelでインストールした後も使えるみたいね。

The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store clients and access tokens

php artisan migrate

Next, you should run the passport:install command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “personal access” and “password grant” clients which will be used to generate access tokens:

After running this command, add the Laravel\Passport\HasApiTokens trait to your App\User model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user’s token and scopes:
Oauth2ってことは、これも認証のところかな。

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

Next, you should call the Passport::routes method within the boot method of your AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

namespace App\Providers;

use Laravel\Passport\Passport;
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 = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

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

        Passport::routes();
    }
}

Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport. This will instruct your application to use Passport’s TokenGuard when authenticating incoming API requests:
なるほど、apiを使うときはconfig/auth.phpを編集するのね。

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Migration Customization
If you are not going to use Passport’s default migrations, you should call the Passport::ignoreMigrations method in the register method of your AppServiceProvider. You may export the default migrations using php artisan vendor:publish –tag=passport-migrations.

By default, Passport uses an integer column to store the user_id. If your application uses a different column type to identify users (for example: UUIDs), you should modify the default Passport migrations after publishing them.
passportの機能がイマイチわからんな。

Frontend Quickstart
In order to use the Passport Vue components, you must be using the Vue JavaScript framework. These components also use the Bootstrap CSS framework. However, even if you are not using these tools, the components serve as a valuable reference for your own frontend implementation.
あ、passportはvue.jsなんだ。vue.jsのプレゼンスすげーな。

Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens. However, it can be time consuming to code a frontend to interact with these APIs. So, Passport also includes pre-built Vue components you may use as an example implementation or starting point for your own implementation.

To publish the Passport Vue components, use the vendor:publish Artisan command:

php artisan vendor:publish --tag=passport-components

The published components will be placed in your resources/js/components directory. Once the components have been published, you should register them in your resources/js/app.js file:
vue.jsで使うjs側の処理

Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

After registering the components, make sure to run npm run dev to recompile your assets. Once you have recompiled your assets, you may drop the components into one of your application’s templates to get started creating clients and personal access tokens:

<passport-clients></passport-clients>
<passport-authorized-clients></passport-authorized-clients>
<passport-personal-access-tokens></passport-personal-access-tokens>

When deploying Passport to your production servers for the first time, you will likely need to run the passport:keys command. This command generates the encryption keys Passport needs in order to generate access token. The generated keys are not typically kept in source control:
keyを使うとのこと。
php artisan passport:keys
If necessary, you may define the path where Passport’s keys should be loaded from. You may use the Passport::loadKeysFrom method to accomplish this:

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

    Passport::routes();

    Passport::loadKeysFrom('/secret-keys/oauth');
}

HTTP Basic Authentication

HTTP Basic Authentication provides a quick way to authenticate users of your application without setting up a dedicated “login” page. To get started, attach the auth.basic middleware to your route. The auth.basic middleware is included with the Laravel framework, so you do not need to define it:

Route::get(‘profile’, function () {
// Only authenticated users may enter…
})->middleware(‘auth.basic’);
[/php]

Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the auth.basic middleware will use the email column on the user record as the “username”.

A Note On FastCGI
If you are using PHP FastCGI, HTTP Basic authentication may not work correctly out of the box. The following lines should be added to your .htaccess file:
あれ、.htaccessなんてあったっけ?

Stateless HTTP Basic Authentication
You may also use HTTP Basic Authentication without setting a user identifier cookie in the session, which is particularly useful for API authentication. To do so, define a middleware that calls the onceBasic method. If no response is returned by the onceBasic method, the request may be passed further into the application:

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Auth;

class AuthenticateOnceWithBasicAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, $next)
    {
        return Auth::onceBasic() ?: $next($request);
    }

}
Route::get('api/user', function () {
    // Only authenticated users may enter...
})->middleware('auth.basic.once');

Logging Out
To manually log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user’s session:

use Illuminate\Support\Facades\Auth;
Auth::logout();

Invalidating Sessions On Other Devices
Laravel also provides a mechanism for invalidating and “logging out” a user’s sessions that are active on other devices without invalidating the session on their current device. Before getting started, you should make sure that the Illuminate\Session\Middleware\AuthenticateSession middleware is present and un-commented in your app/Http/Kernel.php class’ web middleware group:

Then, you may use the logoutOtherDevices method on the Auth facade. This method requires the user to provide their current password, which your application should accept through an input form:

use Illuminate\Support\Facades\Auth;

Auth::logoutOtherDevices($password);

Adding Custom Guards
You may define your own authentication guards using the extend method on the Auth facade. You should place this call to extend within a service provider. Since Laravel already ships with an AuthServiceProvider, we can place the code in that provider:

namespace App\Providers;

use App\Services\Auth\JwtGuard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

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

        Auth::extend('jwt', function ($app, $name, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\Guard...

            return new JwtGuard(Auth::createUserProvider($config['provider']));
        });
    }
}

As you can see in the example above, the callback passed to the extend method should return an implementation of Illuminate\Contracts\Auth\Guard. This interface contains a few methods you will need to implement to define a custom guard. Once your custom guard has been defined, you may use this guard in the guards configuration of your auth.php configuration file:

Closure Request Guards
The simplest way to implement a custom, HTTP request based authentication system is by using the Auth::viaRequest method. This method allows you to quickly define your authentication process using a single Closure.

To get started, call the Auth::viaRequest method within the boot method of your AuthServiceProvider. The viaRequest method accepts a guard name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a Closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, null:

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

    Auth::viaRequest('custom-token', function ($request) {
        return User::where('token', $request->token)->first();
    });
}

Once your custom guard has been defined, you may use this guard in the guards configuration of your auth.php configuration file:

Adding Custom User Providers
If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider. We will use the provider method on the Auth facade to define a custom user provider:

namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use App\Extensions\RiakUserProvider;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

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

        Auth::provider('riak', function ($app, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\UserProvider...

            return new RiakUserProvider($app->make('riak.connection'));
        });
    }
}

The User Provider Contract
The Illuminate\Contracts\Auth\UserProvider implementations are only responsible for fetching a Illuminate\Contracts\Auth\Authenticatable implementation out of a persistent storage system, such as MySQL, Riak, etc. These two interfaces allow the Laravel authentication mechanisms to continue functioning regardless of how the user data is stored or what type of class is used to represent it.

Let’s take a look at the Illuminate\Contracts\Auth\UserProvider contract:

namespace Illuminate\Contracts\Auth;

interface UserProvider {

    public function retrieveById($identifier);
    public function retrieveByToken($identifier, $token);
    public function updateRememberToken(Authenticatable $user, $token);
    public function retrieveByCredentials(array $credentials);
    public function validateCredentials(Authenticatable $user, array $credentials);

}

Manually Authenticating Users

Of course, you are not required to use the authentication controllers included with Laravel. If you choose to remove these controllers, you will need to manage user authentication using the Laravel authentication classes directly. Don’t worry, it’s a cinch!

We will access Laravel’s authentication services via the Auth facade, so we’ll need to make sure to import the Auth facade at the top of the class. Next, let’s check out the attempt method:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array. You should not hash the password specified as the password value, since the framework will automatically hash the value before comparing it to the hashed password in the database. If the two hashed passwords match an authenticated session will be started for the user.

The attempt method will return true if authentication was successful. Otherwise, false will be returned.

The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.
うおおおおおお、なんか無償に作りたくなってきた。
Specifying Additional Conditions
If you wish, you may also add extra conditions to the authentication query in addition to the user’s e-mail and password. For example, we may verify that user is marked as “active”:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

Accessing Specific Guard Instances
You may specify which guard instance you would like to utilize using the guard method on the Auth facade. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file:

if (Auth::guard('admin')->attempt($credentials)) {
    //
}

Logging Out
To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user’s session:

Auth::logout();

Remembering Users
If you would like to provide “remember me” functionality in your application, you may pass a boolean value as the second argument to the attempt method, which will keep the user authenticated indefinitely, or until they manually logout. Of course, your users table must include the string remember_token column, which will be used to store the “remember me” token.

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // The user is being remembered...
}

Other Authentication Methods
Authenticate A User Instance
If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. Of course, the App\User model included with Laravel already implements this interface:

Auth::login($user);

// Login and "remember" the given user...
Auth::login($user, true);
Auth::guard('admin')->login($user);

Authenticate A User By ID
To log a user into the application by their ID, you may use the loginUsingId method. This method accepts the primary key of the user you wish to authenticate:

Auth::loginUsingId(1);

// Login and “remember” the given user…
Auth::loginUsingId(1, true);
Authenticate A User Once
You may use the once method to log a user into the application for a single request. No sessions or cookies will be utilized, which means this method may be helpful when building a stateless API:

if (Auth::once($credentials)) {
//
}

Laravel Authentication

Securityの項目多いなー
Authentication, API Authentication, Authorization, Email Verification, Encryption, Hashing, Password Reset

後半のEncryption, Hashing, Password Resetはロジックに近いか。やはりAuthenticationが肝か。

Introduction
Tip!! Want to get started fast? Just run php artisan make:auth and php artisan migrate in a fresh Laravel application. Then, navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. These two commands will take care of scaffolding your entire authentication system!

php artisan make:authをすると、自動でログイン

Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at config/auth.php, which contains several well documented options for tweaking the behavior of the authentication services.

config/auth.phpの中身を見てみます。

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

ふーん、ここで制御してるんだ。

At its core, Laravel’s authentication facilities are made up of “guards” and “providers”. Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies.

Providers define how users are retrieved from your persistent storage. Laravel ships with support for retrieving users using Eloquent and the database query builder. However, you are free to define additional providers as needed for your application.

Don’t worry if this all sounds confusing now! Many applications will never need to modify the default authentication configuration.

Database Considerations
By default, Laravel includes an App\User Eloquent model in your app directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the database authentication driver which uses the Laravel query builder.

When building the database schema for the App\User model, make sure the password column is at least 60 characters in length. Maintaining the default string column length of 255 characters would be a good choice.

Also, you should verify that your users (or equivalent) table contains a nullable, string remember_token column of 100 characters. This column will be used to store a token for users that select the “remember me” option when logging into your application.
なんだ、Eloquentって。しかし、authは量が多いなー

Authentication Quickstart
Routing
Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:

php artisan make:auth

one lineでOKを売りにしてるけど、これちゃんとやらんとあかんな。

Views
As mentioned in the previous section, the php artisan make:auth command will create all of the views you need for authentication and place them in the resources/views/auth directory.

The make:auth command will also create a resources/views/layouts directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

Authenticating
Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may access your application in a browser since the authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.

Path Customization
When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect location by defining a redirectTo property on the LoginController, RegisterController, ResetPasswordController, and VerificationController:

protected $redirectTo = ‘/’;
Next, you should modify the RedirectIfAuthenticated middleware’s handle method to use your new URI when redirecting the user.

If the redirect path needs custom generation logic you may define a redirectTo method instead of a redirectTo property:

php artisan make:authをすると、resources/viewsの下にauthとlayoutのディレクトリができます。
layoutは普通にviewだ。あ、authも全部viewです。
app/Http/Controllers/Authの下にLoginController.phpなどができてます。
ここで、redirectが書かれます。なるほどー

protected $redirectTo = '/';

protected function redirectTo()
{
    return '/path';
}

Username Customization
By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController:

public function username()
{
    return 'username';
}

usernameに変更もできるとのこと。

Guard Customization
You may also customize the “guard” that is used to authenticate and register users. To get started, define a guard method on your LoginController, RegisterController, and ResetPasswordController. The method should return a guard instance:

use Illuminate\Support\Facades\Auth;

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

guardって何?NGなログインってこと?違うような。。。

Validation / Storage Customization
To modify the form fields that are required when a new user registers with your application, or to customize how new users are stored into your database, you may modify the RegisterController class. This class is responsible for validating and creating new users of your application.

The validator method of the RegisterController contains the validation rules for new users of the application. You are free to modify this method as you wish.

The create method of the RegisterController is responsible for creating new App\User records in your database using the Eloquent ORM. You are free to modify this method according to the needs of your database.
うわー、この辺は、もっと勉強したい。詳しくなりたいな。
ログイン機能は、どのCMSでも重要だからなー

Retrieving The Authenticated User
You may access the authenticated user via the Auth facade:

use Illuminate\Support\Facades\Auth;

// Get the currently authenticated user...
$user = Auth::user();

// Get the currently authenticated user's ID...
$id = Auth::id();
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
    /**
     * Update the user's profile.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        // $request->user() returns an instance of the authenticated user...
    }
}

Determining If The Current User Is Authenticated
To determine if the user is already logged into your application, you may use the check method on the Auth facade, which will return true if the user is authenticated:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

あ、なるほど、bladeではなく、コントローラーでログイン状態かチェックするのか。なるほどね。
Even though it is possible to determine if a user is authenticated using the check method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on protecting routes.

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

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

public function __construct()
{
    $this->middleware('auth');
}

protected function redirectTo($request)
{
    return route('login');
}

Specifying A Guard
When attaching the auth middleware to a route, you may also specify which guard should be used to authenticate the user. The guard specified should correspond to one of the keys in the guards array of your auth.php configuration file:

public function __construct()
{
    $this->middleware('auth:api');
}

Login Throttling
If you are using Laravel’s built-in LoginController class, the Illuminate\Foundation\Auth\ThrottlesLogins trait will already be included in your controller. By default, the user will not be able to login for one minute if they fail to provide the correct credentials after several attempts. The throttling is unique to the user’s username / e-mail address and their IP address.

laravel Compiling Assets (Mix)

やっとフロントの最後。といっても、まだ半分も終わってない。
この量はひどいな。まー凄く勉強にはなるからいいけど。

Introduction
Laravel Mix provides a fluent API for defining Webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors. Through simple method chaining, you can fluently define your asset pipeline. For example:
これヘッダーのところ。最初はデフォルトで色々入ってますよね。

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

If you’ve ever been confused and overwhelmed about getting started with Webpack and asset compilation, you will love Laravel Mix. However, you are not required to use it while developing your application. Of course, you are free to use any asset pipeline tool you wish, or even none at all.

Installation & Setup
Installing Node
Before triggering Mix, you must first ensure that Node.js and NPM are installed on your machine.
ああ、サーバーサイドでもnode.js、javascript、sassなんかは知ってて当然なんだ。なるほどねー

By default, Laravel Homestead includes everything you need; however, if you aren’t using Vagrant, then you can easily install the latest version of Node and NPM using simple graphical installers from their download page.

Laravel Mix
The only remaining step is to install Laravel Mix. Within a fresh installation of Laravel, you’ll find a package.json file in the root of your directory structure. The default package.json file includes everything you need to get started. Think of this like your composer.json file, except it defines Node dependencies instead of PHP. You may install the dependencies it references by running:

Running Mix
Mix is a configuration layer on top of Webpack, so to run your Mix tasks you only need to execute one of the NPM scripts that is included with the default Laravel package.json file:

// Run all Mix tasks...
npm run dev

// Run all Mix tasks and minify output...
npm run production

Watching Assets For Changes
The npm run watch command will continue running in your terminal and watch all relevant files for changes. Webpack will then automatically recompile your assets when it detects a change:

npm run watch
You may find that in certain environments Webpack isn’t updating when your files change. If this is the case on your system, consider using the watch-poll command:

npm run watch-poll
ひょえーーーーーーーーーーー

Working With Stylesheets
The webpack.mix.js file is your entry point for all asset compilation. Think of it as a light configuration wrapper around Webpack. Mix tasks can be chained together to define exactly how your assets should be compiled.

ess
The less method may be used to compile Less into CSS. Let’s compile our primary app.less file to public/css/app.css.

mix.less(‘resources/less/app.less’, ‘public/css’);
Multiple calls to the less method may be used to compile multiple files:

mix.less(‘resources/less/app.less’, ‘public/css’)
.less(‘resources/less/admin.less’, ‘public/css’);
If you wish to customize the file name of the compiled CSS, you may pass a full file path as the second argument to the less method:

mix.less(‘resources/less/app.less’, ‘public/stylesheets/styles.css’);
If you need to override the underlying Less plug-in options, you may pass an object as the third argument to mix.less():

mix.less(‘resources/less/app.less’, ‘public/css’, {
strictMath: true
});

Sass
The sass method allows you to compile Sass into CSS. You may use the method like so:

mix.sass(‘resources/sass/app.scss’, ‘public/css’);
Again, like the less method, you may compile multiple Sass files into their own respective CSS files and even customize the output directory of the resulting CSS:

mix.sass(‘resources/sass/app.sass’, ‘public/css’)
.sass(‘resources/sass/admin.sass’, ‘public/css/admin’);
Additional Node-Sass plug-in options may be provided as the third argument:

mix.sass(‘resources/sass/app.sass’, ‘public/css’, {
precision: 5
});
一応、less, sassはok

Stylus
これは知らん。

Similar to Less and Sass, the stylus method allows you to compile Stylus into CSS:

mix.stylus(‘resources/stylus/app.styl’, ‘public/css’);
You may also install additional Stylus plug-ins, such as Rupture. First, install the plug-in in question through NPM (npm install rupture) and then require it in your call to mix.stylus():

mix.stylus(‘resources/stylus/app.styl’, ‘public/css’, {
use: [
require(‘rupture’)()
]
});
http://stylus-lang.com/
node.js ? sassっぽい。
PostCSS
PostCSS, a powerful tool for transforming your CSS, is included with Laravel Mix out of the box. By default, Mix leverages the popular Autoprefixer plug-in to automatically apply all necessary CSS3 vendor prefixes. However, you’re free to add any additional plug-ins that are appropriate for your application. First, install the desired plug-in through NPM and then reference it in your webpack.mix.js file:

mix.sass('resources/sass/app.scss', 'public/css')
   .options({
        postCss: [
            require('postcss-css-variables')()
        ]
   });

mix.styles([
    'public/css/vendor/normalize.css',
    'public/css/vendor/videojs.css'
], 'public/css/all.css');

videojsは思ったより流行ってませんね。

URL Processing
Because Laravel Mix is built on top of Webpack, it’s important to understand a few Webpack concepts. For CSS compilation, Webpack will rewrite and optimize any url() calls within your stylesheets. While this might initially sound strange, it’s an incredibly powerful piece of functionality. Imagine that we want to compile Sass that includes a relative URL to an image:

.example {
    background: url('../images/example.png');
}

By default, Laravel Mix and Webpack will find example.png, copy it to your public/images folder, and then rewrite the url() within your generated stylesheet. As such, your compiled CSS will be:
As useful as this feature may be, it’s possible that your existing folder structure is already configured in a way you like. If this is the case, you may disable url() rewriting like so:

mix.sass('resources/app/app.scss', 'public/css')
   .options({
      processCssUrls: false
   });

Source Maps
Though disabled by default, source maps may be activated by calling the mix.sourceMaps() method in your webpack.mix.js file. Though it comes with a compile/performance cost, this will provide extra debugging information to your browser’s developer tools when using compiled assets.

mix.js(‘resources/js/app.js’, ‘public/js’)
.sourceMaps();

Working With JavaScript
Mix provides several features to help you work with your JavaScript files, such as compiling ECMAScript 2015, module bundling, minification, and concatenating plain JavaScript files. Even better, this all works seamlessly, without requiring an ounce of custom configuration:

mix.js('resources/js/app.js', 'public/js');

With this single line of code, you may now take advantage of:

ES2015 syntax.
Modules
Compilation of .vue files.
Minification for production environments.

Vendor Extraction
One potential downside to bundling all application-specific JavaScript with your vendor libraries is that it makes long-term caching more difficult. For example, a single update to your application code will force the browser to re-download all of your vendor libraries even if they haven’t changed.

If you intend to make frequent updates to your application’s JavaScript, you should consider extracting all of your vendor libraries into their own file. This way, a change to your application code will not affect the caching of your large vendor.js file. Mix’s extract method makes this a breeze:

mix.js('resources/js/app.js', 'public/js')
   .extract(['vue'])

The extract method accepts an array of all libraries or modules that you wish to extract into a vendor.js file. Using the above snippet as an example, Mix will generate the following files:

public/js/manifest.js: The Webpack manifest runtime
public/js/vendor.js: Your vendor libraries
public/js/app.js: Your application code
To avoid JavaScript errors, be sure to load these files in the proper order:

eact
Mix can automatically install the Babel plug-ins necessary for React support. To get started, replace your mix.js() call with mix.react():

mix.react(‘resources/js/app.jsx’, ‘public/js’);
Behind the scenes, Mix will download and include the appropriate babel-preset-react Babel plug-in.
aaaaaa, reactはよくわかってないぞ。

Vanilla JS
Similar to combining stylesheets with mix.styles(), you may also combine and minify any number of JavaScript files with the scripts() method:

mix.scripts([
‘public/js/admin.js’,
‘public/js/dashboard.js’
], ‘public/js/all.js’);
This option is particularly useful for legacy projects where you don’t require Webpack compilation for your JavaScript.

Tip!! A slight variation of mix.scripts() is mix.babel(). Its method signature is identical to scripts; however, the concatenated file will receive Babel compilation, which translates any ES2015 code to vanilla JavaScript that all browsers will understand.

Custom Webpack Configuration
Behind the scenes, Laravel Mix references a pre-configured webpack.config.js file to get you up and running as quickly as possible. Occasionally, you may need to manually modify this file. You might have a special loader or plug-in that needs to be referenced, or maybe you prefer to use Stylus instead of Sass. In such instances, you have two choices:

Merging Custom Configuration
Mix provides a useful webpackConfig method that allows you to merge any short Webpack configuration overrides. This is a particularly appealing choice, as it doesn’t require you to copy and maintain your own copy of the webpack.config.js file. The webpackConfig method accepts an object, which should contain any Webpack-specific configuration that you wish to apply.

Versioning / Cache Busting
Many developers suffix their compiled assets with a timestamp or unique token to force browsers to load the fresh assets instead of serving stale copies of the code. Mix can handle this for you using the version method.

The version method will automatically append a unique hash to the filenames of all compiled files, allowing for more convenient cache busting:

mix.js(‘resources/js/app.js’, ‘public/js’)
.version();
After generating the versioned file, you won’t know the exact file name. So, you should use Laravel’s global mix function within your views to load the appropriately hashed asset. The mix function will automatically determine the current name of the hashed file:

Because versioned files are usually unnecessary in development, you may instruct the versioning process to only run during npm run production:

mix.js(‘resources/js/app.js’, ‘public/js’);

if (mix.inProduction()) {
mix.version();
}
Browsersync Reloading
BrowserSync can automatically monitor your files for changes, and inject your changes into the browser without requiring a manual refresh. You may enable support by calling the mix.browserSync() method:

mix.browserSync(‘my-domain.test’);

// Or…

// https://browsersync.io/docs/options
mix.browserSync({
proxy: ‘my-domain.test’
});
You may pass either a string (proxy) or object (BrowserSync settings) to this method. Next, start Webpack’s dev server using the npm run watch command. Now, when you modify a script or PHP file, watch as the browser instantly refreshes the page to reflect your changes.

Environment Variables
You may inject environment variables into Mix by prefixing a key in your .env file with MIX_:

MIX_SENTRY_DSN_PUBLIC=http://example.com
After the variable has been defined in your .env file, you may access via the process.env object. If the value changes while you are running a watch task, you will need to restart the task:

process.env.MIX_SENTRY_DSN_PUBLIC
Notifications
When available, Mix will automatically display OS notifications for each bundle. This will give you instant feedback, as to whether the compilation was successful or not. However, there may be instances when you’d prefer to disable these notifications. One such example might be triggering Mix on your production server. Notifications may be deactivated, via the disableNotifications method.

mix.disableNotifications();

laravel JavaScript {{ title }}amp; CSS Scaffolding

Scaffoldingって何だっけ? →日本語訳は足場
なんか色々やった記憶がある。

Introduction
While Laravel does not dictate which JavaScript or CSS pre-processors you use, it does provide a basic starting point using Bootstrap and Vue that will be helpful for many applications. By default, Laravel uses NPM to install both of these frontend packages

JavaScript
Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don’t have to use JavaScript at all. However, Laravel does include some basic scaffolding to make it easier to get started writing modern JavaScript using the Vue library. Vue provides an expressive API for building robust JavaScript applications using components. As with CSS, we may use Laravel Mix to easily compile JavaScript components into a single, browser-ready JavaScript file.
ほう、jsと相性がいいのか。

Removing The Frontend Scaffolding
If you would like to remove the frontend scaffolding from your application, you may use the preset Artisan command. This command, when combined with the none option, will remove the Bootstrap and Vue scaffolding from your application, leaving only a blank SASS file and a few common JavaScript utility libraries:

php artisan preset none

Writing CSS
Laravel’s package.json file includes the bootstrap package to help you get started prototyping your application’s frontend using Bootstrap. However, feel free to add or remove packages from the package.json file as needed for your own application. You are not required to use the Bootstrap framework to build your Laravel application – it is provided as a good starting point for those who choose to use it.

Before compiling your CSS, install your project’s frontend dependencies using the Node package manager (NPM):
nodeね。

Once the dependencies have been installed using npm install, you can compile your SASS files to plain CSS using Laravel Mix. The npm run dev command will process the instructions in your webpack.mix.js file. Typically, your compiled CSS will be placed in the public/css directory:

npm run dev

The default webpack.mix.js included with Laravel will compile the resources/sass/app.scss SASS file. This app.scss file imports a file of SASS variables and loads Bootstrap, which provides a good starting point for most applications. Feel free to customize the app.scss file however you wish or even use an entirely different pre-processor by configuring Laravel Mix

Writing Vue Components
By default, fresh Laravel applications contain an ExampleComponent.vue Vue component located in the resources/js/components directory. The ExampleComponent.vue file is an example of a single file Vue component which defines its JavaScript and HTML template in the same file. Single file components provide a very convenient approach to building JavaScript driven applications. The example component is registered in your app.js file:

Vue.component(
‘example-component’,
require(‘./components/ExampleComponent.vue’)
);

To use the component in your application, you may drop it into one of your HTML templates. For example, after running the make:auth Artisan command to scaffold your application’s authentication and registration screens, you could drop the component into the home.blade.php Blade template:

Of course, if you are interested in learning more about writing Vue components, you should read the Vue documentation, which provides a thorough, easy-to-read overview of the entire Vue framework.
おいおい、ドキュメント読んでばっかりじゃん。なんだこの無限ループは。

Using React
If you prefer to use React to build your JavaScript application, Laravel makes it a cinch to swap the Vue scaffolding with React scaffolding. On any fresh Laravel application, you may use the preset command with the react option:

php artisan preset react
This single command will remove the Vue scaffolding and replace it with React scaffolding, including an example component.

Laravel localization

Introduction
Laravel’s localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application. Language strings are stored in files within the resources/lang directory. Within this directory there should be a subdirectory for each language supported by the application

/resources
    /lang
        /en
            messages.php
        /es
            messages.php

return [
    'welcome' => 'Welcome to our application'
];

最近、ローカライズに携わるの増えてきたなー

Configuring The Locale
The default language for your application is stored in the config/app.php configuration file. Of course, you may modify this value to suit the needs of your application. You may also change the active language at runtime using the setLocale method on the App facade:

Route::get('welcome/{locale}', function ($locale) {
    App::setLocale($locale);

    //
});
$locale = App::getLocale();

if (App::isLocale('en')) {
    //
}

Defining Translation Strings
Using Short Keys
Typically, translation strings are stored in files within the resources/lang directory. Within this directory there should be a subdirectory for each language supported by the application:

/resources
    /lang
        /en
            messages.php
        /es
            messages.php
// resources/lang/en/messages.php

return [
    'welcome' => 'Welcome to our application'
];

毎回思うんだが、translationってどれくらいの精度なんだろう。。
Using Translation Strings As Keys
For applications with heavy translation requirements, defining every string with a “short key” can become quickly confusing when referencing them in your views. For this reason, Laravel also provides support for defining translation strings using the “default” translation of the string as the key.

Translation files that use translation strings as keys are stored as JSON files in the resources/lang directory. For example, if your application has a Spanish translation, you should create a resources/lang/es.json file:

Retrieving Translation Strings
You may retrieve lines from language files using the __ helper function. The __ method accepts the file and key of the translation string as its first argument. For example, let’s retrieve the welcome translation string from the resources/lang/messages.php language file:
contructerみたいなもの?

echo __('messages.welcome');

echo __('I love programming.');

Of course if you are using the Blade templating engine, you may use the {{ }} syntax to echo the translation string or use the @lang directive:

{{ __(‘messages.welcome’) }}

@lang(‘messages.welcome’)
If the specified translation string does not exist, the __ function will return the translation string key. So, using the example above, the __ function would return messages.welcome if the translation string does not exist.

Note: The @lang directive does not escape any output. You are fully responsible for escaping your own output when using this directive.

Replacing Parameters In Translation Strings
If you wish, you may define place-holders in your translation strings. All place-holders are prefixed with a :. For example, you may define a welcome message with a place-holder name:

'welcome' => 'Welcome, :name',
echo __('messages.welcome', ['name' => 'dayle']);
'welcome' => 'Welcome, :NAME', // Welcome, DAYLE
'goodbye' => 'Goodbye, :Name', // Goodbye, Dayle

Pluralization
Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization. By using a “pipe” character, you may distinguish singular and plural forms of a string:

'apples' => 'There is one apple|There are many apples',

'apples' => '{0} There are none|[1,19] There are some|[20,*] There are many',
echo trans_choice('messages.apples', 10);
'minutes_ago' => '{1} :value minute ago|[2,*] :value minutes ago',

echo trans_choice('time.minutes_ago', 5, ['value' => 5]);

Overriding Package Language Files
Some packages may ship with their own language files. Instead of changing the package’s core files to tweak these lines, you may override them by placing files in the resources/lang/vendor/{package}/{locale} directory.

So, for example, if you need to override the English translation strings in messages.php for a package named skyrim/hearthfire, you should place a language file at: resources/lang/vendor/hearthfire/en/messages.php. Within this file, you should only define the translation strings you wish to override. Any translation strings you don’t override will still be loaded from the package’s original language files.

Laravel switch statement

やはり@が初めに来ます。vendor側でbladeの@から始まる構文を読み込んでいるのでしょう。

@switch($i)
    @case(1)
        First case...
        @break

    @case(2)
        Second case...
        @break

    @default
        Default case...
@endswitch

loop
In addition to conditional statements, Blade provides simple directives for working with PHP’s loop structures. Again, each of these directives functions identically to their PHP counterparts

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

@while (true)
    <p>I'm looping forever.</p>
@endwhile

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach

continue, breakもあります。

The Loop Variable
When looping, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

The $loop variable also contains a variety of other useful properties:

Property Description
$loop->index The index of the current loop iteration (starts at 0).
$loop->iteration The current loop iteration (starts at 1).
$loop->remaining The iterations remaining in the loop.
$loop->count The total number of items in the array being iterated.
$loop->first Whether this is the first iteration through the loop.
$loop->last Whether this is the last iteration through the loop.
$loop->depth The nesting level of the current loop.
$loop->parent When in a nested loop, the parent’s loop variable.
forとforeach以外であるんや@loopなんて。

Comments
Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application:

{{– This comment will not be present in the rendered HTML –}}

In some situations, it’s useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template:

@php
    //
@endphp

あーなるほど。laravelはphpと準phpを習っているような感覚に陥るね。cakeはそうでなかったと思うが。

Forms
CSRF Field
Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the @csrf Blade directive to generate the token field:

<form method="POST" action="/profile">
    @csrf

    ...
</form>

Method Field
Since HTML forms can’t make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The @method Blade directive can create this field for you:

<form action="/foo/bar" method="POST">
    @method('PUT')

    ...
</form>

postの中に@method(‘put’)か。

Including Sub-Views
Blade’s @include directive allows you to include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:

<div>
    @include('shared.errors')

    <form>
        <!-- Form Contents -->
    </form>
</div>

Stacks
Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views:

@push('scripts')
    <script src="/example.js"></script>
@endpush

You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the @stack directive:
If you would like to prepend content onto the beginning of a stack, you should use the @prepend directive:

@push('scripts')
    This will be second...
@endpush

// Later...

@prepend('scripts')
    This will be first...
@endprepend

Service Injection
The @inject directive may be used to retrieve a service from the Laravel service container. The first argument passed to @inject is the name of the variable the service will be placed into, while the second argument is the class or interface name of the service you wish to resolve:

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

Extending Blade
Blade allows you to define your own custom directives using the directive method. When the Blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains.

The following example creates a @datetime($var) directive which formats a given $var, which should be an instance of DateTime:

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function ($expression) {
            return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Laravel Blade Templates

Introduction
Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

Template Inheritance
Defining A Layout
Two of the primary benefits of using Blade are template inheritance and sections. To get started, let’s take a look at a simple example. First, we will examine a “master” page layout. Since most web applications maintain the same general layout across various pages, it’s convenient to define this layout as a single Blade view:

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

As you can see, this file contains typical HTML mark-up. However, take note of the @section and @yield directives. The @section directive, as the name implies, defines a section of content, while the @yield directive is used to display the contents of a given section.

Now that we have defined a layout for our application, let’s define a child page that inherits the layout.

Extending A Layout
When defining a child view, use the Blade @extends directive to specify which layout the child view should “inherit”. Views which extend a Blade layout may inject content into the layout’s sections using @section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using @yield:

@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
    @@parent

    <p>This is appended to the master sidebar.</p>
@endsection

@section('content')
    <p>This is my body content.</p>
@endsection

In this example, the sidebar section is utilizing the @@parent directive to append (rather than overwriting) content to the layout’s sidebar. The @@parent directive will be replaced by the content of the layout when the view is rendered.

Tip!! Contrary to the previous example, this sidebar section ends with @endsection instead of @show. The @endsection directive will only define a section while @show will define and immediately yield the section.

Blade views may be returned from routes using the global view helper:

Route::get('blade', function () {
    return view('child');
});

Components & Slots
Components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. First, let’s imagine a reusable “alert” component we would like to reuse throughout our application:

<div class="alert alert-danger">
    {{ $slot }}
</div>

The {{ $slot }} variable will contain the content we wish to inject into the component. Now, to construct this component, we can use the @component Blade directive:

@component('alert')
    <strong>Whoops!</strong> Something went wrong!
@endcomponent

Sometimes it is helpful to define multiple slots for a component. Let’s modify our alert component to allow for the injection of a “title”. Named slots may be displayed by “echoing” the variable that matches their name:

<div class="alert alert-danger">
    <div class="alert-title">{{ $title }}</div>

    {{ $slot }}
</div>

Now, we can inject content into the named slot using the @slot directive. Any content not within a @slot directive will be passed to the component in the $slot variable:

@component('alert')
    @slot('title')
        Forbidden
    @endslot

    You are not allowed to access this resource!
@endcomponent

Passing Additional Data To Components
Sometimes you may need to pass additional data to a component. For this reason, you can pass an array of data as the second argument to the @component directive. All of the data will be made available to the component template as variables:

@component('alert', ['foo' => 'bar'])
    ...
@endcomponent

Aliasing Components
If your Blade components are stored in a sub-directory, you may wish to alias them for easier access. For example, imagine a Blade component that is stored at resources/views/components/alert.blade.php. You may use the component method to alias the component from components.alert to alert. Typically, this should be done in the boot method of your AppServiceProvider:

use Illuminate\Support\Facades\Blade;

Blade::component('components.alert', 'alert');

Once the component has been aliased, you may render it using a directive:

@alert(['type' => 'danger'])
    You are not allowed to access this resource!
@endalert

You may omit the component parameters if it has no additional slots:

@alert
    You are not allowed to access this resource!
@endalert

Displaying Data
You may display data passed to your Blade views by wrapping the variable in curly braces. For example, given the following route:

Route::get('greeting', function () {
    return view('welcome', ['name' => 'Samantha']);
});

You may display the contents of the name variable like so:

Hello, {{ $name }}.

Displaying Unescaped Data
By default, Blade {{ }} statements are automatically sent through PHP’s htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

The current UNIX timestamp is {{ time() }}.
Hello, {!! $name !!}.

Rendering JSON
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:

<script>
    var app = <?php echo json_encode($array); ?>;
</script>

However, instead of manually calling json_encode, you may use the @json Blade directive:

<script>
    var app = @json($array);
</script>
namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::withoutDoubleEncoding();
    }
}

bladeは結構jsの知識が必要だな。

Blade & JavaScript Frameworks
Since many JavaScript frameworks also use “curly” braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

@verbatim
    <div class="container">
        Hello, {{ name }}.
    </div>
@endverbatim

Control Structures
In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts.

If Statements
You may construct if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts:

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

bladeの中だと、if文の書き方が変わる。確か普通にphpでif文で書いても良かったんだっけ。

うわ、auth::check()なんかあるんか。

@unless (Auth::check())
    You are not signed in.
@endunless

これは凄い。

@isset($records)
    // $records is defined and is not null...
@endisset

@empty($records)
    // $records is "empty"...
@endempty

auth, guestのroleはこうやって書くのか、すげー。

@auth('admin')
    // The user is authenticated...
@endauth

@guest('admin')
    // The user is not authenticated...
@endguest

Section Directives
You may check if a section has content using the @hasSection directive:

@hasSection('navigation')
    <div class="pull-right">
        @yield('navigation')
    </div>

    <div class="clearfix"></div>
@endif

理解はできてきたので、きちんと使いこなすレベルまで行きたい。

Laravel Logging

Introduction
To help you learn more about what’s happening within your application, Laravel provides robust logging services that allow you to log messages to files, the system error log, and even to Slack to notify your entire team.

Under the hood, Laravel utilizes the Monolog library, which provides support for a variety of powerful log handlers. Laravel makes it a cinch to configure these handlers, allowing you to mix and match them to customize your application’s log handling.
あーーーーーーーlaravelもslack通知できるんだ!!!

Configuring The Channel Name
By default, Monolog is instantiated with a “channel name” that matches the current environment, such as production or local. To change this value, add a name option to your channel’s configuration:

'stack' => [
    'driver' => 'stack',
    'name' => 'channel-name',
    'channels' => ['single', 'slack'],
],

Available Channel Drivers
Name Description
stack A wrapper to facilitate creating “multi-channel” channels
single A single file or path based logger channel (StreamHandler)
daily A RotatingFileHandler based Monolog driver which rotates daily
slack A SlackWebhookHandler based Monolog driver
syslog A SyslogHandler based Monolog driver
errorlog A ErrorLogHandler based Monolog driver
monolog A Monolog factory driver that may use any supported Monolog handler
custom A driver that calls a specified factory to create a channel

Configuring The Slack Channel
The slack channel requires a url configuration option. This URL should match a URL for an incoming webhook that you have configured for your Slack team.

Building Log Stacks
As previously mentioned, the stack driver allows you to combine multiple channels into a single log channel. To illustrate how to use log stacks, let’s take a look at an example configuration that you might see in a production application:

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['syslog', 'slack'],
    ],

    'syslog' => [
        'driver' => 'syslog',
        'level' => 'debug',
    ],

    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel Log',
        'emoji' => ':boom:',
        'level' => 'critical',
    ],
],

ドライバーで指定して書いていくんだ。

Let’s dissect this configuration. First, notice our stack channel aggregates two other channels via its channels option: syslog and slack. So, when logging messages, both of these channels will have the opportunity to log the message.

Log Levels
Take note of the level configuration option present on the syslog and slack channel configurations in the example above. This option determines the minimum “level” a message must be in order to be logged by the channel. Monolog, which powers Laravel’s logging services, offers all of the log levels defined in the RFC 5424 specification: emergency, alert, critical, error, warning, notice, info, and debug.

So, imagine we log a message using the debug method:

Writing Log Messages
You may write information to the logs using the Log facade. As previously mentioned, the logger provides the eight logging levels defined in the RFC 5424 specification: emergency, alert, critical, error, warning, notice, info and debug:

Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);

So, you may call any of these methods to log a message for the corresponding level. By default, the message will be written to the default log channel as configured by your config/logging.php configuration file:

namespace App\Http\Controllers;

use App\User;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        Log::info('Showing user profile for user: '.$id);

        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

Contextual Information
An array of contextual data may also be passed to the log methods. This contextual data will be formatted and displayed with the log message:

Log::info(‘User failed to login.’, [‘id’ => $user->id]);
Writing To Specific Channels
Sometimes you may wish to log a message to a channel other than your application’s default channel. You may use the channel method on the Log facade to retrieve and log to any channel defined in your configuration file:

Log::channel(‘slack’)->info(‘Something happened!’);
If you would like to create an on-demand logging stack consisting of multiple channels, you may use the stack method:

Log::stack([‘single’, ‘slack’])->info(‘Something happened!’);
Advanced Monolog Channel Customization
Customizing Monolog For Channels
Sometimes you may need complete control over how Monolog is configured for an existing channel. For example, you may want to configure a custom Monolog FormatterInterface implementation for a given channel’s handlers.

To get started, define a tap array on the channel’s configuration. The tap array should contain a list of classes that should have an opportunity to customize (or “tap” into) the Monolog instance after it is created:

'single' => [
    'driver' => 'single',
    'tap' => [App\Logging\CustomizeFormatter::class],
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
],

Once you have configured the custom channel, you’re ready to define the class that will create your Monolog instance. This class only needs a single method: __invoke, which should return the Monolog instance:

namespace App\Logging;
use Monolog\Logger;

class CreateCustomLogger
{
    /**
     * Create a custom Monolog instance.
     *
     * @param  array  $config
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {
        return new Logger(...);
    }
}