通过Laravel 5中的请求清理preg_match不能正常工作

时间:2015-06-12 10:17:47

标签: php laravel preg-match laravel-5 sanitize

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

VideoRequest:

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)时,它将正确返回所有带有嵌入代码的输入,就像一个ID一样。当它传递给rules();嵌入现在是原来的链接?

2 个答案:

答案 0 :(得分:2)

可能使用自定义验证规则,然后使用mutator在模型保存之前提取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());
    }
}

模型

命名空间App;

use Illuminate\Database\Eloquent\Model;

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

答案 1 :(得分:0)

我用

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

获取ID。