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;

        //
    }
}

エンジニアが断捨離するとこうなる

最近、持ち物を断捨離しました。カッコは買値です。

-iphone(10万)
-apple watch(2万)
-金庫(忘れた、2万くらい)
-デスク(1万)
-スーツ全部(20万くらい?)
-Yシャツ全部(不明)
-ネクタイ全部(1万くらい)
-革靴(3万)
-ベルト(忘れた)
-プログラミング関係の本(不明)
-服、ジャケット、ビンテージジーンズ(不明)
-抽象画の絵画(忘れた)
-万年筆(5千円)
-名刺入れ(千円?)
-香水(数千円)

iphoneとApple watchは売った。普通に捨てようかなーと思ってたんだが、じゃんぱらがサクッと30分くらいで買い取ってくれました。
apple watch シリーズ1を2万で買って1年以上使って、バンドや本体など使用感がありましたが1万5千円で買い取り。お得感あるね。iphone 6Sは画面が割れてたので1万3千円くらい。両方ともケース、仕様書などはそろってました。箱を取っておくといいですね。
■じゃんぱら: http://www.janpara.co.jp/
HPページに参考価格が出ますが、商品の状態や付属品などによって値段が変わってくるので、実際にお店に持っていった方がいいと思います。見積りを出してくれるので、気に入らなければ、売らない、と伝えることもできます。

ネクタイはdunhill、Armani、Lanvinなどブランドものばっかりでしたが、費用対効果的に数千円の為に売るのめんどーなので捨てました。万年筆、絵も小銭にはなったのかもしれんけど、特にいいかーって感じで破棄。Pythonの機械学習などの本はamazonに中古で出品してもだいたい定価とほぼ同じ値段で売れますけど、これも手間を考えると、まーいいかなって感じ。
例えばこれ。中古3350円と新品3450円と、100円しか変わらない!これ、ほかの業界からみたら凄いよね。

金庫は一人では持てないくらい重すぎたので、業者呼んで1万5千円払って、机と一緒に処分してもらいました。
昔はお金払って不用品処分するのってかなり抵抗あった。3~4万くらい払って買ったのに、金払って処分って阿保ちやうか、もったいないし、普通に捨てればよくない、と思ってた。
でも最近は考え方が変わって、捨てた方がメリットが大きいと感じたら、金払ってでも処分した方が、長期的には利益になる、と思って、思い切って捨てました。
相見積とったけど、地域の即日対応の業者を選択。全国対応の業者は、050-XXXX-XXXXの電話番号で、かけると数十分後に折り返しかかってくる。値段は1万強で大して変わらない。

絵の価値ってのはよくわらないな~ 個展とか行っても、なんでこの絵がこの値段なのかさっぱりわからない。ぱっと見、いいなと思って買うんだけど、感性が違うから、ぱっと見た印象と値段が合わない。だから売り方も難しい。その曖昧さがいいのかもしれないけど、私には理解できん。昔、ドバイから絵を数十ドルで買って、1万円強で売ったりしてたけど、なんか、手間の割にはって感じで別に面白くないんだよね。

リストの中ではスーツが一番高い。1着10万のスーツがあるからね。エンジニアってスーツいらないけど、スーツ着る機会はありそう、と躊躇して、断捨離するのもこのリストの中では一番最後。しかも、スーツって、基本2万以上で売ってるくせに、aokiや青山など、スーツ小売店は下取りだけで、買取やってないんだね。下取りやって、割引券を渡しているだけ。これっておかしくない?価値の減り方が尋常ではない。aokiとかを見てると、2万のスーツも5万のスーツも10万のスーツも同じ扱いなんだ。しかも、みんなスーツ着てるくせに、スーツ買取業者って極端に少ない。悩んだけど、結局スーツ買取業者に買取りの見積もり取ってもらうことに。
Webフォームで、写真とスーツの詳細を入力すると、数営業日でメールにレスが届く。
なんか、ブランドの買取相場の理由が色々書かれていたが、見積結果は、じゃーん、2着が200~400円、2着が買取り不可。 ※ちなみに10万のスーツは、需要はあるけど値段がつかないって言われた。
は?? え、これ、なにかの冗談でしょ? 400円って。。どういう商売なんだろうこれ。
流石にこれはあかんと思って、オークションに出したら、サクサクっと1万7千円で売れた。そうだよね、俺の感覚はそんなにおかしくない、と少し安心。
それにしても、スーツ業界って闇が深いな。そういえば、ユニクロもカジュアルなジャケットは売ってますが、スーツには深く手を出してないですよね。柳井さんって、非常にロジカルな経営者なので、なんかあるんだろうなーこれ。そーいえば、1着2万円で、2着目千円の利益のカラクリが未だによーわからん。

ついでに書類も色々整理。Web系のドキュメントは大体ネットに落ちてるので、思い切って捨てることに。
世の中、紙の取引は減ってるのに、行政関係は未だに紙ベースが主流ですね。公共サービスはペーパレス化がかなり遅れている気がします。
ということで、大分整理されました。

断捨離まとめ
– デジタル関係は欲しい人に売れば、想像してた値段より売れる、他のものに較べて減損しにくい
– 同じジャンルの商品を大量に扱ってる人に価値を見てもらえば市場価格で売れる
– スーツや洋服は袖通したら価値が減る、今後高値で買う必要は全くない
– サイズが大きな家具類は捨てにくい、買い取ってもらうにも、持ち運びのハードルが高く、売り方もわからない

知識があるものは、価値がわかるけど、知識がないと価値がわからんってことか。

Laravel Basic conroller

Basic Controllers
Defining Controllers
Below is an example of a basic controller class. Note that the controller extends the base controller class included with Laravel. The base class provides a few convenience methods such as the middleware method, which may be used to attach middleware to controller actions:

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

You can define a route to this controller action like so:

Route::get('user/{id}', 'UserController@show');

UserControllerでは、user.profileを表示する

Now, when a request matches the specified route URI, the show method on the UserController class will be executed. Of course, the route parameters will also be passed to the method.

Controllers are not required to extend a base class. However, you will not have access to convenience features such as the middleware, validate, and dispatch methods.

Controllers & Namespaces
It is very important to note that we did not need to specify the full controller namespace when defining the controller route. Since the RouteServiceProvider loads your route files within a route group that contains the namespace, we only specified the portion of the class name that comes after the App\Http\Controllers portion of the namespace.

If you choose to nest your controllers deeper into the App\Http\Controllers directory, use the specific class name relative to the App\Http\Controllers root namespace. So, if your full controller class is App\Http\Controllers\Photos\AdminController, you should register routes to the controller like so:

Route::get('foo', 'Photos\AdminController@method');

Single Action Controllers
If you would like to define a controller that only handles a single action, you may place a single __invoke method on the controller:

namespace App\Http\Controllers;

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

class ShowProfile extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function __invoke($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

When registering routes for single action controllers, you do not need to specify a method:

Route::get(‘user/{id}’, ‘ShowProfile’);
You may generate an invokable controller by using the –invokable option of the make:controller Artisan command:

php artisan make:controller ShowProfile –invokable
artisanコマンド

Controller Middleware
Middleware may be assigned to the controller’s routes in your route files:

Route::get('profile', 'UserController@show')->middleware('auth');

でたーmiddleware

lass UserController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log')->only('index');

        $this->middleware('subscribed')->except('store');
    }
}

Controllers also allow you to register middleware using a Closure. This provides a convenient way to define a middleware for a single controller without defining an entire middleware class:

$this->middleware(function ($request, $next) {
    // ...

    return $next($request);
});

Laravel Controller

Introduction
Instead of defining all of your request handling logic as Closures in route files, you may wish to organize this behavior using Controller classes. Controllers can group related request handling logic into a single class. Controllers are stored in the app/Http/Controllers directory.

Laravel CSRF Protection

Laravel CSRF Protection
フォームやデータを扱うと、CSRF対策は必須になってくる。

Introduction
Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF “token” for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

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>

CSRF Tokens & JavaScript
When building JavaScript driven applications, it is convenient to have your JavaScript HTTP library automatically attach the CSRF token to every outgoing request. By default, the resources/js/bootstrap.js file registers the value of the csrf-token meta tag with the Axios HTTP library. If you are not using this library, you will need to manually configure this behavior for your application.
jsでtokenか。確かに言われてみれば、できるでしょうね。でも、jsでやるメリットはあるのか。。

Excluding URIs From CSRF Protection
Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

online payment
https://stripe.com/jp
こんなん流行ってるんだ。知らんかった。

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

うーん
X-CSRF-TOKEN
In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a HTML meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

え、メタに入れんの?

Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

By default, the resources/js/bootstrap.js file registers the value of the csrf-token meta tag with the Axios HTTP library. If you are not using this library, you will need to manually configure this behavior for your application.

X-XSRF-TOKEN
Laravel stores the current CSRF token in a XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header.

This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN header.
おーなんだかなー