更新记录时的laravel自定义验证规则

时间:2019-01-30 19:56:40

标签: php laravel validation laravel-5 eloquent

我有2个表格用于“课程模型”中的“系列”和“课程”。我将课程与某个系列相关联,我创建了一个自定义验证规则,以防止在同一系列中重复在课程表中使用相同的Episode_number,并且效果很好,但是在更新时,我希望排除此课程。 / p>

这是我的课程表:

public function up()
{
    Schema::create('lessons', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('series_id');
        $table->string('title');
        $table->text('description');
        $table->unsignedInteger('episode_number');
        $table->unsignedInteger('video_id')->unique();
        $table->boolean('premium')->default(0);
        $table->timestamps();

        $table->unique(['series_id', 'episode_number']);
    });
}

这是课程模型中的口才关系函数:

public function series()
{
    return $this->belongsTo(Series::class);
}

这是我的自定义验证规则:

<?php
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class uniqueSeriesLessonValidation implements Rule
{
public $id;
/**
 * Create a new rule instance.
 *
 * @return void
 */
public function __construct($id)
{
    $this->id = $id;
}

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{
    $count = DB::table('lessons')->where('episode_number', $value)
        ->where('series_id', $this->id)
        ->count();

    if ($count === 0){
        return true;
    }

    return false;

}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'The lesson title should not be repeated in the same series twice.';
}
}

这是我在创建新课程时的验证,可以很好地防止同一系列两次重复同一课程的Episode_number:

public function rules(Request $request)
{
    return [
        'title' => 'required',
        'description' => 'required',
        'episode_number' => ['required',new uniqueSeriesLessonValidation($request->series_by_id->id)],
        'video_id' => 'required|unique:lessons|numeric'
    ];
}

这是我在更新课程时的验证,问题是:

public function rules(Request $request)
{
    return [
        'title' => 'required',
        'description' => 'required',
        'episode_number' => ['required',new uniqueSeriesLessonValidation($request->series_by_id->id),$request->lesson->id],
        'video_id' => 'required'
    ];
}

2 个答案:

答案 0 :(得分:0)

这是因为它认为$request->lesson->id是一个单独的角色。如果您还想将该值传递给角色,请作为参数来执行。

new uniqueSeriesLessonValidation($request->series_by_id->id,$request->lesson->id)

答案 1 :(得分:0)

谢谢大家,我通过在更新时添加第二个参数来解决它,并且在接收到该参数时通过更改规则使创建为空