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(...);
    }
}

Laravel Error handling

Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user. We’ll dive deeper into this class throughout this documentation.
既に実装されているらしい。

Configuration
The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.

For local development, you should set the APP_DEBUG environment variable to true. In your production environment, this value should always be false. If the value is set to true in production, you risk exposing sensitive configuration values to your application’s end users.

The Report Method
All exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. We’ll examine each of these methods in detail. The report method is used to log exceptions or send them to an external service like Bugsnag or Sentry. By default, the report method passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish.

For example, if you need to report different types of exceptions in different ways, you may use the PHP instanceof comparison operator:

public function report(Exception $exception)
{
    if ($exception instanceof CustomException) {
        //
    }

    return parent::report($exception);
}

The report Helper
Sometimes you may need to report an exception but continue handling the current request. The report helper function allows you to quickly report an exception using your exception handler’s report method without rendering an error page:

public function isValid($value)
{
    try {
        // Validate the value...
    } catch (Exception $e) {
        report($e);

        return false;
    }
}

Ignoring Exceptions By Type
The $dontReport property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:

protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    \Illuminate\Database\Eloquent\ModelNotFoundException::class,
    \Illuminate\Validation\ValidationException::class,
];

Reportable & Renderable Exceptions

namespace App\Exceptions;

use Exception;

class RenderException extends Exception
{
    /**
     * Report the exception.
     *
     * @return void
     */
    public function report()
    {
        //
    }

    /**
     * Render the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        return response(...);
    }
}

Some exceptions describe HTTP error codes from the server. For example, this may be a “page not found” error (404), an “unauthorized error” (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort helper:

abort(404);
The abort helper will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:

abort(403, ‘Unauthorized action.’);
Custom HTTP Error Pages
Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable:

{{ $exception->getMessage() }}

abort, カスタマイズなど対応している。

Form Request Validation

Creating Form Requests
For more complex validation scenarios, you may wish to create a “form request”. Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

php artisan make:request StoreBlogPost

The generated class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Let’s add a few validation rules to the rules method:

public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

public function store(StoreBlogPost $request)
{
    // The incoming request is valid...

    // Retrieve the validated input data...
    $validated = $request->validated();
}

例のvalidationを定義するってやつですね。
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
確かにajaxですと違いますね。

Adding After Hooks To Form Requests
If you would like to add an “after” hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

これはわからん。
Authorizing Form Requests
The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update:

public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}
/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

なるほど、充実してますなー

Manually Creating Validators

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }
}

Automatic Redirection
If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the requests’s validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

Named Error Bags
If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. Pass a name as the second argument to withErrors

return redirect('register')
            ->withErrors($validator, 'login');
{{ $errors->login->first('email') }}

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Available Validation Rules
AcceptedActive URLAfter (Date)After Or Equal (Date)AlphaAlpha DashAlpha NumericArrayBailBefore (Date)Before Or Equal (Date)BetweenBooleanConfirmedDateDate EqualsDate FormatDifferentDigitsDigits BetweenDimensions (Image Files)DistinctE-MailExists (Database)FileFilledGreater ThanGreater Than Or EqualImage (File)InIn ArrayIntegerIP AddressJSONLess ThanLess Than Or EqualMaxMIME TypesMIME Type By File ExtensionMinNot InNot RegexNullableNumericPresentRegular ExpressionRequiredRequired IfRequired UnlessRequired WithRequired With AllRequired WithoutRequired Without AllSameSizeStringTimezoneUnique (Database)URLUUID
これはやべーやつだ。

Conditionally Adding Rules
Validating When Present
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list: