Php 在Laravel 5中通过请求进行消毒预配,但未按预期工作
我有一个功能,可以在YouTube链接保存到数据库之前对其进行清理。我的preg_匹配工作正常,但我无法将经过消毒的版本(仅YouTube ID)传递回控制器,它会还原未初始化的原始链接 视频请求:Php 在Laravel 5中通过请求进行消毒预配,但未按预期工作,php,laravel,preg-match,laravel-5,sanitize,Php,Laravel,Preg Match,Laravel 5,Sanitize,我有一个功能,可以在YouTube链接保存到数据库之前对其进行清理。我的preg_匹配工作正常,但我无法将经过消毒的版本(仅YouTube ID)传递回控制器,它会还原未初始化的原始链接 视频请求: public function rules() { $this->sanitize(); return [ 'page_id' => 'required|integer', 'visibility' => 'required',
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();
}
当Idd($input)
位于sanitize()函数底部时,它将正确返回所有带有嵌入代码的输入,就像ID一样。当它传递到rules()时;嵌入现在是原始链接吗?我使用
/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/
要获取ID。可能需要使用自定义验证规则,然后在模型保存之前使用mutator提取YouTube ID。 路线
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);
}
}
我在清理数据时没有遇到问题,我在将清理后的数据传递给rules()时遇到问题;谢谢Rob,我已经看过了这些文档,但对我来说没有多大意义(这还是一个新概念)。大致来说,将此实现为自定义验证的逻辑是什么?谢谢Rob,这是一种享受,并解释了它:)