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:

Laravel Validation

Laravel provides several different approaches to validate your application’s incoming data. By default, Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

Validation Quickstart
To learn about Laravel’s powerful validation features, let’s look at a complete example of validating a form and displaying the error messages back to the user.

Defining The Routes
First, let’s assume we have the following routes defined in our routes/web.php file:

Route::get('post/create', 'PostController@create');
Route::post('post', 'PostController@store');
namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Show the form to create a new blog post.
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate and store the blog post...
    }
}

validation logic
基本コントローラーで作るのね。

public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

So, in our example, the user will be redirected to our controller’s create method when validation fails, allowing us to display the error messages in the view:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

A Note On Optional Fields
By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application’s global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your “optional” request fields as nullable if you do not want the validator to consider null values as invalid. For example:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

知識をupdateしないとあかんね。

AJAX Requests & Validation
In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
ajaxの場合、対応が異なる様。

Laravel Session

Introduction
Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. Laravel ships with a variety of session backends that are accessed through an expressive, unified API. Support for popular backends such as Memcached, Redis, and databases is included out of the box.
sessionも色々な使い方があるようです。なるほど、これは勉強になります。

Configuration
The session configuration file is stored at config/session.php. Be sure to review the options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications. In production applications, you may consider using the memcached or redis drivers for even faster session performance.

The session driver configuration option defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:

file – sessions are stored in storage/framework/sessions.
cookie – sessions are stored in secure, encrypted cookies.
database – sessions are stored in a relational database.
memcached / redis – sessions are stored in one of these fast, cache based stores.
array – sessions are stored in a PHP array and will not be persisted.
まず、config/session.phpを見てみたいと思います。
項目があまりないです。

'cookie' => env(
        'SESSION_COOKIE',
        str_slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),

Database
When using the database session driver, you will need to create a table to contain the session items. Below is an example Schema declaration for the table:

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->unsignedInteger('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

uniqe, nullableはわかる。primary keyは自動か?

You may use the session:table Artisan command to generate this migration:

php artisan session:table
php artisan migrate

Redis
Before using Redis sessions with Laravel, you will need to install the predis/predis package (~1.0) via Composer. You may configure your Redis connections in the database configuration file. In the session configuration file, the connection option may be used to specify which Redis connection is used by the session.

Using The Session
Retrieving Data
There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance. First, let’s look at accessing the session via a Request instance, which can be type-hinted on a controller method. Remember, controller method dependencies are automatically injected via the Laravel service container:

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function show(Request $request, $id)
    {
        $value = $request->session()->get('key');

        //
    }
}

You may also use the global session PHP function to retrieve and store data in the session. When the session helper is called with a single, string argument, it will return the value of that session key. When the helper is called with an array of key / value pairs, those values will be stored in the session:

Route::get('home', function () {
    // Retrieve a piece of data from the session...
    $value = session('key');

    // Specifying a default value...
    $value = session('key', 'default');

    // Store a piece of data in the session...
    session(['key' => 'value']);
});

Retrieving All Session Data
If you would like to retrieve all the data in the session, you may use the all method:

$data = $request->session()->all();

Storing Data
To store data in the session, you will typically use the put method or the session helper:

// Via a request instance...
$request->session()->put('key', 'value');

// Via the global helper...
session(['key' => 'value']);

Pushing To Array Session Values
The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so:

$request->session()->push('user.teams', 'developers');

Retrieving & Deleting An Item
The pull method will retrieve and delete an item from the session in a single statement:

$value = $request->session()->pull('key', 'default');

Flash Data
Sometimes you may wish to store items in the session only for the next request. You may do so using the flash method. Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted. Flash data is primarily useful for short-lived status messages:

$request->session()->flash('status', 'Task was successful!');

Adding Custom Session Drivers

namespace App\Extensions;

class MongoSessionHandler implements \SessionHandlerInterface
{
    public function open($savePath, $sessionName) {}
    public function close() {}
    public function read($sessionId) {}
    public function write($sessionId, $data) {}
    public function destroy($sessionId) {}
    public function gc($lifetime) {}
}

namespace App\Providers;

use App\Extensions\MongoSessionHandler;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\ServiceProvider;

class SessionServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Session::extend('mongo', function ($app) {
            // Return implementation of SessionHandlerInterface...
            return new MongoSessionHandler;
        });
    }

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

Laravel URL generation

Laravel provides several helpers to assist you in generating URLs for your application. Of course, these are mainly helpful when building links in your templates and API responses, or when generating redirect responses to another part of your application.
URLをつくるねー

The Basics
Generating Basic URLs
The url helper may be used to generate arbitrary URLs for your application. The generated URL will automatically use the scheme (HTTP or HTTPS) and host from the current request:

$post = App\Post::find(1);
echo url("/posts/{$post->id}");
// http://example.com/posts/1

Accessing The Current URL
If no path is provided to the url helper, a Illuminate\Routing\UrlGenerator instance is returned, allowing you to access information about the current URL:

// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();
// Get the full URL for the previous request...
echo url()->previous();

URLs For Named Routes
The route helper may be used to generate URLs to named routes. Named routes allow you to generate URLs without being coupled to the actual URL defined on the route. Therefore, if the route’s URL changes, no changes need to be made to your route function calls. For example, imagine your application contains a route defined like the following:

Route::get('/post/{post}', function () {
    //
})->name('post.show');

echo route('post.show', ['post' => 1]);

// http://example.com/post/1

Eloquent modelsの意味がわからん。
echo route(‘post.show’, [‘post’ => $post]);

Laravel allows you to easily create “signed” URLs to named routes. These URLs have a “signature” hash appended to the query string which allows Laravel to verify that the URL has not been modified since it was created. Signed URLs are especially useful for routes that are publicly accessible yet need a layer of protection against URL manipulation.

For example, you might use signed URLs to implement a public “unsubscribe” link that is emailed to your customers. To create a signed URL to a named route, use the signedRoute method of the URL facade:
あーなるほど。というか、全てsignedRouteになるのか。

use Illuminate\Support\Facades\URL;
return URL::signedRoute('unsubscribe', ['user' => 1]);

use Illuminate\Support\Facades\URL;
return URL::temporarySignedRoute(
    'unsubscribe', now()->addMinutes(30), ['user' => 1]
);

hasValidSignatureって、ログイン状態と違うのか?普通のphpなら、ログイン状態かsessionをみて判断するけど。

use Illuminate\Http\Request;

Route::get('/unsubscribe/{user}', function (Request $request) {
    if (! $request->hasValidSignature()) {
        abort(401);
    }

    // ...
})->name('unsubscribe');

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
];

URLs For Controller Actions
The action function generates a URL for the given controller action. You do not need to pass the full namespace of the controller. Instead, pass the controller class name relative to the App\Http\Controllers namespace:
個別に見ていくしかないのか

$url = action('HomeController@index');

use App\Http\Controllers\HomeController;
$url = action([HomeController::class, 'index']);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetDefaultLocaleForUrls
{
    public function handle($request, Closure $next)
    {
        URL::defaults(['locale' => $request->user()->locale]);
        return $next($request);
    }
}

あ、次がsessionだから、いよいよ本丸登場だ。

Laravel views

Views contain the HTML served by your application and separate your controller / application logic from your presentation logic. Views are stored in the resources/views directory. A simple view might look something like this:

<!-- View stored in resources/views/greeting.blade.php -->

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

Since this view is stored at resources/views/greeting.blade.php, we may return it using the global view helper like so:

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

As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory. The second argument is an array of data that should be made available to the view. In this case, we are passing the name variable, which is displayed in the view using Blade syntax.

Of course, views may also be nested within sub-directories of the resources/views directory. “Dot” notation may be used to reference nested views. For example, if your view is stored at resources/views/admin/profile.blade.php, you may reference it like so:

return view('admin.profile', $data);

Determining If A View Exists
If you need to determine if a view exists, you may use the View facade. The exists method will return true if the view exists:

use Illuminate\Support\Facades\View;

if (View::exists('emails.customer')) {
    //
}

Of course, you may also call this method via the View facade:

use Illuminate\Support\Facades\View;

return View::first([‘custom.admin’, ‘admin’], $data);
When passing information in this manner, the data should be an array with key / value pairs. Inside your view, you can then access each value using its corresponding key, such as . As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view:

return view(‘greeting’)->with(‘name’, ‘Victoria’);

Sharing Data With All Views
Occasionally, you may need to share a piece of data with all views that are rendered by your application. You may do so using the view facade’s share method. Typically, you should place calls to share within a service provider’s boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them:

namespace App\Providers;

use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

For this example, let’s register the view composers within a service provider. We’ll use the View facade to access the underlying Illuminate\Contracts\View\Factory contract implementation. Remember, Laravel does not include a default directory for view composers. You are free to organize them however you wish. For example, you could create an app/Http/ViewComposers directory:
view composerはcomposerではなく、laravelの機能としてのcomposerか。

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using class based composers...
        View::composer(
            'profile', 'App\Http\ViewComposers\ProfileComposer'
        );

        // Using Closure based composers...
        View::composer('dashboard', function ($view) {
            //
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

View::composer(
‘profile’, ‘App\Http\ViewComposers\ProfileComposer’
);と書くのか、書き方が変わってる。

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use App\Repositories\UserRepository;

class ProfileComposer
{
/**
* The user repository implementation.
*
* @var UserRepository
*/
protected $users;

/**
* Create a new profile composer.
*
* @param UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
// Dependencies automatically resolved by service container…
$this->users = $users;
}

/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with(‘count’, $this->users->count());
}
}
Just before the view is rendered, the composer’s compose method is called with the Illuminate\View\View instance. You may use the with method to bind data to the view.

Tip!! All view composers are resolved via the service container, so you may type-hint any dependencies you need within a composer’s constructor.

Attaching A Composer To Multiple Views
You may attach a view composer to multiple views at once by passing an array of views as the first argument to the composer method:

View::composer(
[‘profile’, ‘dashboard’],
‘App\Http\ViewComposers\MyViewComposer’
);
The composer method also accepts the * character as a wildcard, allowing you to attach a composer to all views:

View::composer(‘*’, function ($view) {
//
});
View Creators
View creators are very similar to view composers; however, they are executed immediately after the view is instantiated instead of waiting until the view is about to render. To register a view creator, use the creator method:

View::creator(‘profile’, ‘App\Http\ViewCreators\ProfileCreator’);