0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LaravelでYouTube動画のIDが有効かどうかを検証する

Posted at

問題

  • YouTube動画のIDが有効かどうかを簡単に検証したい
  • バリデーションメッセージを日本語化したい

環境

以下で検証

  • Debian GNU Linux 10
  • PHP 7.1
  • Laravel 5.5

使用ライブラリ

こちらを使用

https://github.com/alaouy/Youtube
v 2.2.5を使用

方法

Request

app/Http/Requests/YouTubeVideoRequest.phpを作成して
rules()に以下を追加

YouTubeVideoRequest.php

    public function rules()
    {
        return [
            'source_url' => [
                'bail',
                // これを追加
                new YoutubeVideoRule,
                Rule::unique('posts')->where( function($query){
                    return $query
                    ->where('user_id','=' , $this->user()->user_id)
                    ->where('deleted_at',null);
                }),
                'required', 
                'regex:/(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i',
            ],

            //...省略...

        ];
    }

このままではバリデーションメッセージが英語のままである。
原因は

ソースの最下部、return部分で

return 'The supplied URL does not look like a Youtube URL.';

となっているため。

Rules

今回はカスタムルールを作成するので、ついでにRules.phpに追加

YouTubeVideoRule.php
// ...省略...
use Alaouy\Youtube\Facades\Youtube;
// ...省略...
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        try {
            // ...何らかのバリデーション
            $videoId = Youtube::parseVidFromURL($value);
            $video = Youtube::getVideoInfo($videoId, ['id']);

        } catch (\Exception $exception) {
            return false;
        }

        return $video != false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        //ここで __()をつけておく
        return __('The supplied URL does not look like a Youtube URL.');
    }
lang/ja.json

{
  "The supplied URL does not look like a Youtube URL.": "URLが無効です"
}

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?