LoginSignup
16
11

More than 5 years have passed since last update.

laravel5.5の変更点覚え書き リリースノート編

Last updated at Posted at 2017-08-31

リリースノートより

非公式ドキュメント(日本語訳)のリリースノートなどを見ながら追加していきます。
全部見ていくのは辛くなったので、気になるものだけ抜粋。

Package Discovery

パッケージインストール時に必要だった、config/app.phpへの登録(providersaliases)が不要になる
(パッケージ側のcomposer.jsonの設定による)

image.png

API Resources

API構築時などにEloquentと実際に返却されるjsonの差を埋める変換レイヤーとしてResourceクラスの追加。(App\Http\Resources

コンストラクタでEloquent(もしくはそのコレクション)を渡すことで$this->id$this->collectionなどの形でモデルにアクセスできる。

Validation Rule Objects

以前はValidator::extendを用いて、クロージャを追加していたカスタムバリデーションだが、
5.5ではRuleクラスとして追加することが可能になった。

使用例
use App\Rules\ValidName;

$this->validate($request, [
    'name' => ['required', new ValidName],
]);

Trusted Proxy Integration

fideloper/TrustedProxyパッケージが5.5からApp\Http\Middleware\TrustProxiesとして同梱された。

これは以下のような理由に起因した状態を防ぐもの。

ロードバランサの背後にあるアプリケーションを実行すると、アプリケーションでHTTPSリンクが生成されないことがあります。通常、これは、アプリケーションがロードバランサからのトラフィックがポート80で転送されており、セキュアなリンクが生成されることがわからないためです。

(これパッケージあったんだ…気付かなかった)

Renderable & Reportable Exceptions

以前のバージョンではそれぞれのExceptionに対する処理をカスタマイズするため、App\Exceptions\Handlerなどで型チェックを行っていたが、
5.5では、Exceptionそれ自体にrender()report()を追加することが出来る。

以前
/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($exception instanceof SpecialException) {
        return response(...);
    }

    return parent::render($request, $exception);
}
5.5
<?php

namespace App\Exceptions;

use Exception;

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

    /**
     * Report the exception.
     *
     * @param  \Illuminate\Http\Request
     * @return void
     */
    public function render($request)
    {
        return response(...);
    }
}

Request Validation

Illuminate\Http\Requestからvalidate()が生やせるようになった。
また、RequestだけでなくControllervalidate()も返り値がvoidでなくなり、検証ルールの属性でonly()されたものが返されるようになった。

Illuminate\Foundation\Providers\FoundationServiceProvider.php
    /**
     * Register the "validate" macro on the request.
     *
     * @return void
     */
    public function registerRequestValidate()
    {
        Request::macro('validate', function (array $rules, ...$params) {
            validator()->validate($this->all(), $rules, ...$params);

            return $this->only(array_keys($rules));
        });
    }
validate()の返り値変更
    public function store(Request $request)
    {
        $validated = $request->([
            'key1' => 'required',
        ]); 

        // $request->all() = ['key1' => 'value1', 'key2' => 'value2']
        // $validated = ['key1' => 'value1']

        //...
    }

Consistent Exception Handling

バリデーション例外処理をApp\Exceptions\Handlerにて一括設定できるようになった。

デフォルトの書式
    /**
     * Convert a validation exception into a response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Validation\ValidationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function invalid($request, ValidationException $exception)
    {
        $url = $exception->redirectTo ?? url()->previous();

        return redirect($url)
                ->withInput($request->except($this->dontFlash))
                ->withErrors(
                    $exception->errors(),
                    $exception->errorBag
                );
    }

    /**
     * Convert a validation exception into a JSON response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Validation\ValidationException  $exception
     * @return \Illuminate\Http\JsonResponse
     */
    protected function invalidJson($request, ValidationException $exception)
    {
        return response()->json([
            'message' => $exception->getMessage(),
            'errors' => $exception->errors(),
        ], $exception->status);
    }

Blade Improvements

@if(auth()->check()) ... @else ... @endifなどとしていた条件分岐を、もっと宣言的に行えるようにした

AppServiceProvider
/**
 * Perform post-registration booting of services.
 *
 * @return void
 */
public function boot()
{
    Blade::if('env', function ($environment) {
        return app()->environment($environment);
    });
}
blade
@env('local')
    // The application is in the local environment...
@else
    // The application is not in the local environment...
@endenv

また、それに伴いユーザーの認証状態を確認できる新しい@auth@guestなどのディレクティブの追加

16
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
11