通过 Laravel 5 中的请求清理 preg_match 无法正常工作

Sanitizing preg_match via Request in Laravel 5 not working as it should

我有一个功能,可以在将 YouTube link 保存到数据库之前对其进行清理。我的 preg_match 工作正常,但我无法将经过清理的版本(只是 YouTube ID)传回控制器,它会还原未清理的原始版本 link。

视频请求:

public function rules()
{
    $this->sanitize();

    return [
        'page_id' => 'required|integer',
        'visibility' => 'required',
        'item_type' => 'required',
        'title' => 'required|string',
        'embed' => 'required',
        'content' => '',
        'image' => 'string',
        'order' => 'required|integer'
    ];
}

public function sanitize()
{
    $input = $this->all();

    if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $input['embed'], $match)) {
        $input['embed'] = $match[1];
    } else {
        return "Please try another YouTube URL or link";
    }

    $this->replace($input);
}

视频控制器:

public function store(VideoRequest $request)
{
    $video = array_intersect_key(Input::all(), $request->rules());
    VideoItem::create($video);
    flash()->success('New video created');
    return redirect()->back();
}

当我在 sanitize() 函数底部 dd($input) 时,它将 return 所有输入正确嵌入代码,就像一个 ID。当它传递给 rules();嵌入现在是原来的 link?

我用

/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/

获取ID。

也许可以使用自定义验证规则,然后在模型保存之前使用修改器来提取 YouTube id。 http://laravel.com/docs/5.0/validation#custom-validation-rules

http://laravel.com/docs/5.0/eloquent#accessors-and-mutators

路线

Route::post('post', 'PostController@store');

 /**
  * Extract Youtube id from url
  * @todo: move to helpers file
  */
function sanitiseHelper ($value) {

    if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $value, $match)) {
        return $match[1];
    }

    return false;
}

控制器

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        Validator::extend('sanitise', function($attribute, $value, $parameters)
        {
            return sanitiseHelper($value);
        });

        $validator = Validator::make($request->all(), [
            'YoutubeUrl' => 'sanitise'
        ], ['sanitise' => 'Please try another YouTube URL or link']);

        if ($validator->fails()) {
            return $validator->errors()->all();
        }

        // Save
        Post::create($request->all());
    }
}

型号

命名空间应用;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function setYouTubeUrlAttribute($value)
    {
        $this->attributes['YouTubeUrl'] = sanitiseHelper($value);
    }
}