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’);

Laravel JSON Responses

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);

If you would like to create a JSONP response, you may use the json method in combination with the withCallback method:

return response()
            ->json(['name' => 'Abigail', 'state' => 'CA'])
            ->withCallback($request->input('callback'));
 File Downloads

File Downloads
The download method may be used to generate a response that forces the user’s browser to download the file at the given path. The download method accepts a file name as the second argument to the method, which will determine the file name that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

return response()->download($pathToFile)->deleteFileAfterSend();

File Responses

return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * Register the application's response macros.
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('caps', function ($value) {
            return Response::make(strtoupper($value));
        });
    }
}

Laravel Creating Responses

Strings & Arrays
All routes and controllers should return a response to be sent back to the user’s browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:
ルーティングに戻るのか。

Route::get('/', function () {
    return 'Hello World';
});

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

Route::get('/', function () {
    return [1, 2, 3];
});

Response Objects
Typically, you won’t just be returning simple strings or arrays from your route actions. Instead, you will be returning full Illuminate\Http\Response instances or views.

Returning a full Response instance allows you to customize the response’s HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, which provides a variety of methods for building HTTP responses:

Route::get('home', function () {
    return response('Hello World', 200)
                  ->header('Content-Type', 'text/plain');
});

Attaching Headers To Responses
Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');
return response($content)
            ->withHeaders([
                'Content-Type' => $type,
                'X-Header-One' => 'Header Value',
                'X-Header-Two' => 'Header Value',
            ]);

Attaching Cookies To Responses
The cookie method on response instances allows you to easily attach cookies to the response. For example, you may use the cookie method to generate a cookie and fluently attach it to the response instance like so:

return response($content)
                ->header('Content-Type', $type)
                ->cookie('name', 'value', $minutes);

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP’s native setcookie method:

Alternatively, you can use the Cookie facade to “queue” cookies for attachment to the outgoing response from your application. The queue method accepts a Cookie instance or the arguments needed to create a Cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

Cookie::queue(Cookie::make('name', 'value', $minutes));

Cookie::queue('name', 'value', $minutes);

Cookies & Encryption
By default, all cookies generated by Laravel are encrypted and signed so that they can’t be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the $except property of the App\Http\Middleware\EncryptCookies middleware, which is located in the app/Http/Middleware directory:

/**
 * The names of the cookies that should not be encrypted.
 *
 * @var array
 */
protected $except = [
    'cookie_name',
];

Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:
Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group or has all of the session middleware applied:

Route::get('dashboard', function () {
    return redirect('home/dashboard');
});
Route::post('user/profile', function () {
    // Validate the request...

    return back()->withInput();
});

When you call the redirect helper with no parameters, an instance of Illuminate\Routing\Redirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method:

Redirecting To Controller Actions
You may also generate redirects to controller actions. To do so, pass the controller and action name to the action method. Remember, you do not need to specify the full namespace to the controller since Laravel’s RouteServiceProvider will automatically set the base controller namespace:

return redirect()->action(‘HomeController@index’);
If your controller route requires parameters, you may pass them as the second argument to the action method:

return redirect()->action(
‘UserController@profile’, [‘id’ => 1]
);

Redirecting To External Domains
Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

return redirect()->away('https://www.google.com');

Redirecting With Flashed Session Data
Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:

Route::post('user/profile', function () {
    // Update the user's profile...

    return redirect('dashboard')->with('status', 'Profile updated!');
});

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

The response helper may be used to generate other types of response instances. When the response helper is called without arguments, an implementation of the Illuminate\Contracts\Routing\ResponseFactory contract is returned. This contract provides several helpful methods for generating responses.

If you need control over the response’s status and headers but also need to return a view as the response’s content, you should use the view method:

return response()
            ->view('hello', $data, 200)
            ->header('Content-Type', $type);

Of course, if you do not need to pass a custom HTTP status code or custom headers, you should use the global view helper function.

Laravel flash

Flashing Input To The Session
The flash method on the Illuminate\Http\Request class will flash the current input to the session so that it is available during the user’s next request to the application:

$request->flash();

flashとか枯れた技術だよなー
You may also use the flashOnly and flashExcept methods to flash a subset of the request data to the session. These methods are useful for keeping sensitive information such as passwords out of the session:

$request->flashOnly(['username', 'email']);

$request->flashExcept('password');

Flashing Input Then Redirecting
Since you often will want to flash input to the session and then redirect to the previous page, you may easily chain input flashing onto a redirect using the withInput method:

return redirect('form')->withInput();

return redirect('form')->withInput(
    $request->except('password')
);

Retrieving Old Input
To retrieve flashed input from the previous request, use the old method on the Request instance. The old method will pull the previously flashed input data from the session:

$username = $request->old(‘username’);
Laravel also provides a global old helper. If you are displaying old input within a Blade template, it is more convenient to use the old helper. If no old input exists for the given field, null will be returned:

input type=”text” name=”username” value=”{{ old(‘username’) }}”
old helpereって、old付けてるだけだけど、どう違うんだ。

Cookies
Retrieving Cookies From Requests
All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. To retrieve a cookie value from the request, use the cookie method on a Illuminate\Http\Request instance:

$value = $request->cookie('name');
$value = Cookie::get('name');

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP’s native setcookie method:

return response(‘Hello World’)->cookie(
‘name’, ‘value’, $minutes, $path, $domain, $secure, $httpOnly
);
Alternatively, you can use the Cookie facade to “queue” cookies for attachment to the outgoing response from your application. The queue method accepts a Cookie instance or the arguments needed to create a Cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

Cookie::queue(Cookie::make(‘name’, ‘value’, $minutes));

Cookie::queue(‘name’, ‘value’, $minutes);
Generating Cookie Instances
If you would like to generate a Symfony\Component\HttpFoundation\Cookie instance that can be given to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

$cookie = cookie(‘name’, ‘value’, $minutes);

return response(‘Hello World’)->cookie($cookie);

$file = $request->file('photo');
$file = $request->photo;

You may determine if a file is present on the request using the hasFile method:
おお、fileが凄い簡単に扱える。
Validating Successful Uploads
In addition to checking if the file is present, you may verify that there were no problems uploading the file via the isValid method:

if ($request->file('photo')->isValid()) {
    //
}

File Paths & Extensions
The UploadedFile class also contains methods for accessing the file’s fully-qualified path and its extension. The extension method will attempt to guess the file’s extension based on its contents. This extension may be different from the extension that was supplied by the client:

$path = $request->photo->path();

$extension = $request->photo->extension();
Other File Methods
There are a variety of other methods available on UploadedFile instances. Check out the API documentation for the class for more information regarding these methods.

$path = $request->photo->store('images');
$path = $request->photo->store('images', 's3');
$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');

Configuring Trusted Proxies
When running your applications behind a load balancer that terminates TLS / SSL certificates, you may notice your application sometimes does not generate HTTPS links. Typically this is because your application is being forwarded traffic from your load balancer on port 80 and does not know it should generate secure links.

To solve this, you may use the App\Http\Middleware\TrustProxies middleware that is included in your Laravel application, which allows you to quickly customize the load balancers or proxies that should be trusted by your application. Your trusted proxies should be listed as an array on the $proxies property of this middleware. In addition to configuring the trusted proxies, you may configure the proxy $headers that should be trusted:

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = [
        '192.168.1.1',
        '192.168.1.2',
    ];

    /**
     * The headers that should be used to detect proxies.
     *
     * @var string
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

Retrieving A Portion Of The Input Data

Retrieving A Portion Of The Input Data
If you need to retrieve a subset of the input data, you may use the only and except methods. Both of these methods accept a single array or a dynamic list of arguments:

$input = $request->only(['username', 'password']);
$input = $request->only('username', 'password');
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');

onlyとexpectの違いは?

Determining If An Input Value Is Present
You should use the has method to determine if a value is present on the request. The has method returns true if the value is present on the request:
ここらへんは分かり易い。

if ($request->has('name')) {
    //
}
if ($request->has(['name', 'email'])) {
    //
}
if ($request->filled('name')) {
    //
}

Laravel Accessing The Request

To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container:
ん、インジェクションを維持する?どういう意味だ?

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Store a new user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $name = $request->input('name');
        //
    }
}

store(Request $request) だから、requestが来た値をnameに保存するというclassです。

Dependency Injection & Route Parameters
If your controller method is also expecting input from a route parameter you should list your route parameters after your other dependencies. For example, if your route is defined like so:
ルートパラメーターを書くべきとしている。

Route::put('user/{id}', 'UserController@update');
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Update the specified user.
     *
     * @param  Request  $request
     * @param  string  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

リクエストを受け取って、レスポンスを返すclass。update(Request $request, $id)としか書いてないけど。

Accessing The Request Via Route Closures
You may also type-hint the Illuminate\Http\Request class on a route Closure. The service container will automatically inject the incoming request into the Closure when it is executed:

use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
    //
});

これは一緒な気がする。

The Illuminate\Http\Request instance provides a variety of methods for examining the HTTP request for your application and extends the Symfony\Component\HttpFoundation\Request class. We will discuss a few of the most important methods below.

Retrieving The Request Path
The path method returns the request’s path information. So, if the incoming request is targeted at http://domain.com/foo/bar, the path method will return foo/bar:
The is method allows you to verify that the incoming request path matches a given pattern. You may use the * character as a wildcard when utilizing this method:

if ($request->is('admin/*')) {
    //
}

ワイルドカードです。

Retrieving The Request URL
To retrieve the full URL for the incoming request you may use the url or fullUrl methods. The url method will return the URL without the query string, while the fullUrl method includes the query string:

// Without Query String...
$url = $request->url();

// With Query String...
$url = $request->fullUrl();

また変なのが出てきた。documentというか用語集に近いか。
PSR-7 Requests
The PSR-7 standard specifies interfaces for HTTP messages, including requests and responses. If you would like to obtain an instance of a PSR-7 request instead of a Laravel request, you will first need to install a few libraries. Laravel uses the Symfony HTTP Message Bridge component to convert typical Laravel requests and responses into PSR-7 compatible implementations:
laravelのリクエストからPSR-7に変える意味が分からん。

composer require symfony/psr-http-message-bridge
composer require zendframework/zend-diactoros

Once you have installed these libraries, you may obtain a PSR-7 request by type-hinting the request interface on your route Closure or controller method:
libraryをcomposerでインストールするのか。classが変わった。

use Psr\Http\Message\ServerRequestInterface;

Route::get('/', function (ServerRequestInterface $request) {
    //
});

If you return a PSR-7 response instance from a route or controller, it will automatically be converted back to a Laravel response instance and be displayed by the framework.

Input Trimming & Normalization
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. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.

If you would like to disable this behavior, you may remove the two middleware from your application’s middleware stack by removing them from the $middleware property of your App\Http\Kernel class.
middlewareとリクエストの関係性がわからんぞ。

Retrieving Input
Retrieving All Input Data
You may also retrieve all of the input data as an array using the all method:
allでくくってしまえ、という例

$input = $request->all();

Retrieving An Input Value
Using a few simple methods, you may access all of the user input from your Illuminate\Http\Request instance without worrying about which HTTP verb was used for the request. Regardless of the HTTP verb, the input method may be used to retrieve user input:

$name = $request->input('name');
$name = $request->input('name', 'Sally');
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');

ワイルドカードを上手く使う。
Retrieving Input From The Query String
While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string:
queryって検索か?

$name = $request->query('name');
$query = $request->query();

Retrieving Input Via Dynamic Properties
You may also access user input using dynamic properties on the Illuminate\Http\Request instance. For example, if one of your application’s forms contains a name field, you may access the value of the field like so:
$name = $request->name;
When using dynamic properties, Laravel will first look for the parameter’s value in the request payload. If it is not present, Laravel will search for the field in the route parameters.

Laravel Specifying The Resource Model

Specifying The Resource Model
If you are using route model binding and would like the resource controller’s methods to type-hint a model instance, you may use the –model option when generating the controller:

php artisan make:controller PhotoController --resource --model=Photo

Spoofing Form Methods
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>

Partial Resource Routes
When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions:

Route::resource('photos', 'PhotoController')->only([
    'index', 'show'
]);

Route::resource('photos', 'PhotoController')->except([
    'create', 'store', 'update', 'destroy'
]);

API Resource Routes
When declaring resource routes that will be consumed by APIs, you will commonly want to exclude routes that present HTML templates such as create and edit. For convenience, you may use the apiResource method to automatically exclude these two routes:

Route::apiResource('photos', 'PhotoController');

Route::apiResources([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);

Naming Resource Routes
By default, all resource controller actions have a route name; however, you can override these names by passing a names array with your options:

Route::resource('photos', 'PhotoController')->names([
    'create' => 'photos.build'
]);

Naming Resource Route Parameters
By default, Route::resource will create the route parameters for your resource routes based on the “singularized” version of the resource name. You can easily override this on a per resource basis by using the parameters method. The array passed into the parameters method should be an associative array of resource names and parameter names:

Localizing Resource URIs
By default, Route::resource will create resource URIs using English verbs. If you need to localize the create and edit action verbs, you may use the Route::resourceVerbs method. This may be done in the boot method of your AppServiceProvider:

use Illuminate\Support\Facades\Route;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Route::resourceVerbs([
        'create' => 'crear',
        'edit' => 'editar',
    ]);
}
Once the verbs have been customized, a resource route registration such as Route::resource('fotos', 'PhotoController') will produce the following URIs:

/fotos/crear

/fotos/{foto}/editar

Supplementing Resource Controllers
If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to Route::resource; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes:

Route::get('photos/popular', 'PhotoController@method');

Route::resource('photos', 'PhotoController');

Method Injection
In addition to constructor injection, you may also type-hint dependencies on your controller’s methods. A common use-case for method injection is injecting the Illuminate\Http\Request instance into your controller methods:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Store a new user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $name = $request->name;

        //
    }
}